//the text to link code (uriaggressive) is from Kim A. Brandt. See http://userscripts.org/scripts/show/7122
const SS_uriaggressive = /[a-z][a-z0-9+-.]*:((\/\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:]|%[a-f0-9]{2})*@)?((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])|([a-z0-9-\._~!$&'\(\)\/\*\+,;=]|%[a-f0-9]{2})+(:[0-9]+)?(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)|(\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)?)|(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*))+(\?([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?(#([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?/i;
const SS_uri = /((http)s?|(ftp)|(mailto)):((\/\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:]|%[a-f0-9]{2})*@)?((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])|([a-z0-9-\._~!$&'\(\)\/\*\+,;=]|%[a-f0-9]{2})+(:[0-9]+)?(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)|(\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)?)|(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*))+(\?([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?(#([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?/i;

const SS_uri2_57 = /[a-z0-9+-.(@)?]*\b\.((name)|([A-za-z]){2,3})\b([A-Za-z0-9$_+-=!*();&%/?:~.]*)?/i;
const SS_uri2_56 = /[a-z0-9+-.(@)?]*\b\.(com|net|org|edu|uk|au)\b([A-Za-z0-9$_+-=!*();&%/?:~.]*)?/i;

const SS_uri2 = /[^\.\(\)\"\s:-][a-z0-9+-.\(@\)?]*\b\.(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=&%/?:~])*([\.,*;!\(\)](?=[-A-Za-z0-9$_+=*\(\);&%/?:~]))*)*/i;
const SS_uri2RnD2 = /[^\.\(\)\"\s:]{1,}(([a-z0-9+-.\(@\)?]+\.)*(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=&%/?:~])*([\.,*;!\(\)](?=[-A-Za-z0-9$_+=*\(\);&%/?:~]))*)*)/i;
// const SS_uri2_66 = /[^\.\(\)\"\s:][a-z0-9+-\(@\)?]*\b\.(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=&%/?:~])*([\.,*;!\(\)](?=[-A-Za-z0-9$_+=*\(\);&%/?:~]))*)*/i;
const SS_uri2_63_1 = /(([-A-Za-z0-9$_+=()&%/?:~])*([\.,*;!@](?=[-A-Za-z0-9$_+=*();&%/?:~]))*)*\b\.(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=()&%/?:~])*([\.,*;!](?=[-A-Za-z0-9$_+=*();&%/?:~]))*)*/i;
const SS_uri2RnD = /(([-A-Za-z0-9$_+=&%~])*([\.@](?=[A-Za-z0-9]))?)*\.(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=()&%/?:~])*([\.,*;!](?=[-A-Za-z0-9$_+=*();&%/?:~]))*)*/i;

const SS_illegal = /^(a|button|label|legend|option|script|select|style|textarea|title)$/i;

var SS_prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
var SS_alertTimeOut = 1000;

const SS_ulreplacement = "<u>$1</u>";

//pref consts
const SMACK_AUTOURL   = "extensions.swaksmack.autourl_boolpref1";
const SMACK_EASYURL   = "extensions.swaksmack.easyurl_boolpref1";
const SMACK_MAXURL = "extensions.swaksmack.maxurl_boolpref1";
const SMACK_MAXLENGTH = "extensions.swaksmack.maxurllength_intpref";
const SMACK_TRUNCURL = "extensions.swaksmack.truncurl_stringpref";
const SMACK_OUTWITALERT = "extensions.swaksmack.outwitwarn_pref1";
const SMACK_OUTWITVOTEALERT = "extensions.swaksmack.outwitvotewarn_pref1";
const SMACK_OUTWITRANDOM = "extensions.swaksmack.outwitrandom_pref1";
const SMACK_GURUGUESSALERT = "extensions.swaksmack.guruguesswarn_pref1";
const SMACK_SMACKPOTALERT = "extensions.swaksmack.smackpotwarn_pref1";
const SMACK_POLLINTERVAL = "extensions.swaksmack.pollinterval_intpref";
const SMACK_ALTALERTMONITOR = "extensions.swaksmack.altalertmonitor_boolpref1";
const SMACK_ENABKEALERTMONITORDELAY = "extensions.swaksmack.enablealertmonitor_boolpref1";

const SMACK_GLOBAL_ENABLEHL = "extensions.swaksmack.hl.enablehl_boolpref1";

const SMACK_THEME_ENABLE = "extensions.swaksmack.theme.enabletheme_boolpref1";
const SMACK_THEME_CHATTC = "extensions.swaksmack.theme.textcolor1_stringpref";
const SMACK_THEME_CHATBTC = "extensions.swaksmack.theme.bkcolor1_stringpref";
const SMACK_THEME_CHATNICK = "extensions.swaksmack.theme.chatNick_stringpref";
const SMACK_THEME_CHATGURU = "extensions.swaksmack.theme.chatGuru_stringpref";
const SMACK_THEME_CHATTIME = "extensions.swaksmack.theme.chatTime_stringpref";
const SMACK_THEME_CHATACTIONS = "extensions.swaksmack.theme.chatActions_stringpref";
const SMACK_THEME_CHATLINKS = "extensions.swaksmack.theme.chatLinks_stringpref";
const SMACK_THEME_BKGRD = "extensions.swaksmack.theme.cBkgrd_stringpref";
const SMACK_THEME_USERTHEMES = "extensions.swaksmack.theme.userThemes_stringpref";
const SMACK_THEME_CURRENTTHEME = "extensions.swaksmack.theme.currentTheme_stringpref";

//these are grouped with the ignore options for the sake of how the current comment processing is performed
const SMACK_ENABLECAPSUPRESSION = "extensions.swaksmack.ignore.enableCapsSupression_boolpref1";
const SMACK_CAPSTHESHOLD = "extensions.swaksmack.ignore.enableCapsThreshold_intpref1";

const SMACK_IGNORECASEHL = "extensions.swaksmack.hl.ignorecasehl_boolpref1";
const SMACK_IGNORESPHL = "extensions.swaksmack.hl.ignoreselfposts_boolpref1";
const SMACK_ENABLELRHL = "extensions.swaksmack.hl.enableinlrhl_boolpref1";
//const SMACK_KEYWORDHL1 = "extensions.swaksmack.keywordshl1_stringpref";
//const SMACK_TCHL1 = "extensions.swaksmack.hltextcolor1_stringpref";
//const SMACK_BTCHL1 = "extensions.swaksmack.hlbkcolor1_stringpref";
//const SMACK_UNDERLINEHL1 = "extensions.swaksmack.hlunderline1_boolpref1";
const SMACK_ITALICHL1 = "extensions.swaksmack.hlitalic1_boolpref1";
const SMACK_BOLDHL1 = "extensions.swaksmack.hlbold1_boolpref1";
//const SMACK_CHATWILDCARD = "extensions.swaksmack.chatwildcard_boolpref1";
const SMACK_BLOCKWILDCARD = "extensions.swaksmack.blockwildcard_boolpref1";
//const SMACK_OUTLINEHL1 = "extensions.swaksmack.postoutlinehl_boolpref1";
//const SMACK_USERNAMEONLYHL1 = "extensions.swaksmack.usernameonlyhl_boolpref1";
//const SMACK_WORDONLYHL1 = "extensions.swaksmack.wordonlyhl_boolpref1";
//const SMACK_USERNAMEHL1 = "extensions.swaksmack.usernamehl1_stringpref";
const SMACK_HL_ENABLEJFEMPLOYEE = "extensions.swaksmack.hl.enableJFEmployee_boolpref1";
const SMACK_HL_JFEMPLOYEEOPT = "extensions.swaksmack.hl.jellyfishemployee_stringpref";
const SMACK_HL_DYNKWOPT = "extensions.swaksmack.hl.dynamickeyword_stringpref";
const SMACK_HL_DYNUNOPT = "extensions.swaksmack.hl.dynamicusername_stringpref";

const SMACK_ENABLEHL1 = "extensions.swaksmack.hl.enablehl1_boolpref1";
const SMACK_KEYWORDHL1 = "extensions.swaksmack.hl.keywordshl1_stringpref";
const SMACK_USERNAMEHL1 = "extensions.swaksmack.hl.usernamehl1_stringpref";
const SMACK_TCHL1 = "extensions.swaksmack.hl.hltextcolor1_stringpref";
const SMACK_BTCHL1 = "extensions.swaksmack.hl.hlbkcolor1_stringpref";
const SMACK_OUTLINEHL1 = "extensions.swaksmack.hl.postoutlinehl1_boolpref1"
const SMACK_USERNAMEONLYHL1 = "extensions.swaksmack.hl.usernameonlyhl1_boolpref1";
const SMACK_CHATWILDCARD1 = "extensions.swaksmack.hl.chatwildcard1_boolpref1";
const SMACK_UNDERLINEHL1 = "extensions.swaksmack.hl.hlunderline1_boolpref1";
const SMACK_WORDONLYHL1 = "extensions.swaksmack.hl.wordonlyhl1_boolpref1";
const SMACK_CHATINFOHL1 = "extensions.swaksmack.hl.chatinfohl1_boolpref1";

const SMACK_ENABLEHL2 = "extensions.swaksmack.hl.enablehl2_boolpref1";
const SMACK_KEYWORDHL2 = "extensions.swaksmack.hl.keywordshl2_stringpref";
const SMACK_USERNAMEHL2 = "extensions.swaksmack.hl.usernamehl2_stringpref";
const SMACK_TCHL2 = "extensions.swaksmack.hl.hltextcolor2_stringpref";
const SMACK_BTCHL2 = "extensions.swaksmack.hl.hlbkcolor2_stringpref";
const SMACK_OUTLINEHL2 = "extensions.swaksmack.hl.postoutlinehl2_boolpref1"
const SMACK_USERNAMEONLYHL2 = "extensions.swaksmack.hl.usernameonlyhl2_boolpref1";
const SMACK_CHATWILDCARD2 = "extensions.swaksmack.hl.chatwildcard2_boolpref1";
const SMACK_UNDERLINEHL2 = "extensions.swaksmack.hl.hlunderline2_boolpref1";
const SMACK_WORDONLYHL2 = "extensions.swaksmack.hl.wordonlyhl2_boolpref1";
const SMACK_CHATINFOHL2 = "extensions.swaksmack.hl.chatinfohl2_boolpref1";

const SMACK_ENABLEHL3 = "extensions.swaksmack.hl.enablehl3_boolpref1";
const SMACK_KEYWORDHL3 = "extensions.swaksmack.hl.keywordshl3_stringpref";
const SMACK_USERNAMEHL3 = "extensions.swaksmack.hl.usernamehl3_stringpref";
const SMACK_TCHL3 = "extensions.swaksmack.hl.hltextcolor3_stringpref";
const SMACK_BTCHL3 = "extensions.swaksmack.hl.hlbkcolor3_stringpref";
const SMACK_OUTLINEHL3 = "extensions.swaksmack.hl.postoutlinehl3_boolpref1"
const SMACK_USERNAMEONLYHL3 = "extensions.swaksmack.hl.usernameonlyhl3_boolpref1";
const SMACK_CHATWILDCARD3 = "extensions.swaksmack.hl.chatwildcard3_boolpref1";
const SMACK_UNDERLINEHL3 = "extensions.swaksmack.hl.hlunderline3_boolpref1";
const SMACK_WORDONLYHL3 = "extensions.swaksmack.hl.wordonlyhl3_boolpref1";
const SMACK_CHATINFOHL3 = "extensions.swaksmack.hl.chatinfohl3_boolpref1";

const SMACK_ENABLEIGNORE1 = "extensions.swaksmack.ignore.enableignoreposts_boolpref1";
const SMACK_FUNIGNORE1 = "extensions.swaksmack.ignore.funignore_boolpref1";
const SMACK_IGNORELIST1 = "extensions.swaksmack.ignore.ignorelist1_stringpref";
const SMACK_IGNORELIST2 = "extensions.swaksmack.ignore.ignorelist2_stringpref";
const SMACK_IGNORELISTATTEND = "extensions.swaksmack.ignore.ignorelistattend1_stringpref";
const SMACK_CHATSPEED = "extensions.swaksmack.adv.chatspeed_intpref";
const SMACK_AUDIOGLOBALENABLE = "extensions.swaksmack.audio.global_enable_boolpref";
const SMACK_AUDIOSOUND_OUTWIT = "extensions.swaksmack.audio.outwitsound_stringpref";
const SMACK_CHECKPMCHAT = "extensions.swaksmack.pmchatcheck_boolpref1";
const SMACK_ENHANCEDCHATUI = "extensions.swaksmack.enhancedChatUI_boolpref";
const SMACK_ENHANCEDCHATUIICONS = "extensions.swaksmack.enhancedChatUIIcons_boolpref";
const SMACK_ENHANCEHIDEAVATARS = "extensions.swaksmack.enhancedHideAvatars_boolpref";
const SMACK_SBSALEINTERVAL = "extensions.swaksmack.statusbarsaleinterval_intpref";
const SMACK_DISPLAYPMSTATUSBAR = "extensions.swaksmack.appearance.displaystatusbarpm_boolpref1";
const SMACK_DISPLAYLRSTATUSBAR = "extensions.swaksmack.appearance.displaystatusbarlr_boolpref1";
const SMACK_DISPLAYKWSTATUSBAR = "extensions.swaksmack.appearance.displaystatusbarkw_boolpref1";
const SMACK_DISPLAYSALESTATUSBAR = "extensions.swaksmack.appearance.displaystatusbarsale_boolpref1";
const SMACK_TINYURLENABLE = "extensions.swaksmack.tinyurl_enable_boolpref1";
const SMACK_TINYURLLENGTH = "extensions.swaksmack.tinyurl_maxurllength_intpref";
const SMACK_REPLYPREFIX = "extensions.swaksmack.replyprefix_stringpref";
const SMACK_REPLYSUFFIX = "extensions.swaksmack.replysuffix_stringpref";
const SMACK_TINYURLPREVIEW = "extensions.swaksmack.tinyurl_enablepreview_boolpref";
const SMACK_ALERTGLOABLEENABLE = "extensions.swaksmack.alerts.global_enable_boolpref";

const SMACK_CHECKPMINTERVAL = "extensions.swaksmack.options.pmcheckinterval_intpref";
const SMACK_MINPMPOLLINTERVAL = "extensions.swaksmack.options.minpmcheckinterval_intpref";


const SMACK_STAT_COLLECT = "extensions.swaksmack.stats.collectstats_boolpref1";
const SMACK_STAT_OW_OPTINCOUNT = "extensions.swaksmack.stats.outwitoptin_intpref";
const SMACK_STAT_OW_SELECTED = "extensions.swaksmack.stats.outwitselected_intpref";
const SMACK_STAT_OW_VOTECOUNT = "extensions.swaksmack.stats.outwitvoted_intpref";
const SMACK_STAT_OW_POINTCOUNT = "extensions.swaksmack.stats.outwitpoints_intpref";
const SMACK_STAT_OW_WINCOUNT = "extensions.swaksmack.stats.outwitwon_intpref";
const SMACK_STAT_SP_PLAYED = "extensions.swaksmack.stats.smackpotplayed_intpref";
const SMACK_STAT_SP_COINBETCOUNT = "extensions.swaksmack.stats.smackpotcoinsguessed_intpref";
const SMACK_STAT_SP_COINWONCOUNT = "extensions.swaksmack.stats.smackpotcoinswon_intpref";
const SMACK_STAT_GG_PLAYED = "extensions.swaksmack.stats.guruguessplayed_intpref";

// These could be defaults to fill a user config list
const SEARCH_FROOGLE_URL = "http://www.google.com/products?q=SMACK_PROD";
const SEARCH_SMACKOSHAME_URL = "http://smackofshame.com/archives.html?q=SMACK_PROD"
const SEARCH_AMAZON_URL = "http://www.amazon.com/exec/obidos/external-search?mode=blended&keyword=SMACK_PROD"
const SEARCH_EBAY_URL = "http://search.ebay.com/search/search.dll?MfcISAPICommand=GetResult&ht=1&SortProperty=MetaEndSort&query=SMACK_PROD";

//break the prefs into option items groups
//these grouping will allow the reseting of different categories (e.g. ignore, audio,etc)
var SMACK_OPTIONITEMS = [SMACK_AUTOURL,SMACK_EASYURL,SMACK_MAXURL,SMACK_MAXLENGTH,SMACK_ALTALERTMONITOR,SMACK_ENABKEALERTMONITORDELAY,
SMACK_TRUNCURL,SMACK_OUTWITALERT,SMACK_OUTWITVOTEALERT,SMACK_OUTWITRANDOM,SMACK_GURUGUESSALERT,SMACK_SMACKPOTALERT,SMACK_BLOCKWILDCARD,
SMACK_CHECKPMCHAT,SMACK_CHECKPMINTERVAL,SMACK_MINPMPOLLINTERVAL,SMACK_ENHANCEDCHATUI,SMACK_TINYURLENABLE,SMACK_TINYURLLENGTH,
SMACK_SBSALEINTERVAL,SMACK_ENHANCEDCHATUIICONS,SMACK_ENHANCEHIDEAVATARS,SMACK_REPLYPREFIX,SMACK_REPLYSUFFIX,
SMACK_TINYURLPREVIEW,SMACK_ALERTGLOABLEENABLE
];

var SMACK_HIGHLIGHT_OPTIONITEMS =[SMACK_GLOBAL_ENABLEHL,SMACK_HL_ENABLEJFEMPLOYEE,SMACK_IGNORECASEHL,SMACK_IGNORESPHL,
SMACK_ENABLELRHL,SMACK_HL_DYNUNOPT,SMACK_HL_DYNKWOPT,SMACK_HL_JFEMPLOYEEOPT,
SMACK_ENABLEHL1,SMACK_KEYWORDHL1,SMACK_USERNAMEONLYHL1,SMACK_OUTLINEHL1,SMACK_USERNAMEHL1,SMACK_CHATWILDCARD1,
SMACK_TCHL1,SMACK_BTCHL1,SMACK_UNDERLINEHL1,SMACK_ITALICHL1,SMACK_BOLDHL1,SMACK_WORDONLYHL1,SMACK_CHATINFOHL1,
SMACK_ENABLEHL2,SMACK_KEYWORDHL2,SMACK_USERNAMEONLYHL2,SMACK_OUTLINEHL2,SMACK_USERNAMEHL2,SMACK_CHATWILDCARD2,
SMACK_TCHL2,SMACK_BTCHL2,SMACK_UNDERLINEHL2,SMACK_WORDONLYHL2,SMACK_CHATINFOHL2,
SMACK_ENABLEHL3,SMACK_KEYWORDHL3,SMACK_USERNAMEONLYHL3,SMACK_OUTLINEHL3,SMACK_USERNAMEHL3,SMACK_CHATWILDCARD3,
SMACK_TCHL3,SMACK_BTCHL3,SMACK_UNDERLINEHL3,SMACK_WORDONLYHL3,SMACK_CHATINFOHL3
];

var SMACK_THEME_OPTIONITEMS = [SMACK_THEME_CHATTC,SMACK_THEME_CHATBTC,SMACK_THEME_ENABLE,SMACK_THEME_CHATNICK,
SMACK_THEME_CHATGURU,SMACK_THEME_CHATTIME,SMACK_THEME_CHATACTIONS,SMACK_THEME_CHATLINKS,SMACK_THEME_BKGRD,
SMACK_THEME_CURRENTTHEME
];

var SMACK_IGNORE_OPTIONITEMS = [SMACK_ENABLEIGNORE1,SMACK_IGNORELIST1,SMACK_IGNORELIST2,
SMACK_IGNORELISTATTEND,SMACK_FUNIGNORE1,
SMACK_ENABLECAPSUPRESSION,SMACK_CAPSTHESHOLD
];

var SMACK_ADV_OPTIONITEMS = [SMACK_CHATSPEED
];

var SMACK_AUDIO_OPTIONITEMS = [SMACK_AUDIOSOUND_OUTWIT,SMACK_AUDIOGLOBALENABLE
];

var SMACK_APPEARANCE_OPTIONITEMS = [
SMACK_DISPLAYPMSTATUSBAR,SMACK_DISPLAYLRSTATUSBAR,SMACK_DISPLAYKWSTATUSBAR,SMACK_DISPLAYSALESTATUSBAR
];

var SMACK_STATS_OPTIONITEMS = [SMACK_STAT_COLLECT,SMACK_STAT_OW_OPTINCOUNT,SMACK_STAT_OW_SELECTED,SMACK_STAT_OW_VOTECOUNT,SMACK_STAT_OW_POINTCOUNT,
SMACK_STAT_OW_WINCOUNT,SMACK_STAT_SP_PLAYED,SMACK_STAT_SP_COINBETCOUNT,SMACK_STAT_SP_COINWONCOUNT,SMACK_STAT_GG_PLAYED
];

//div ids used to find outwit opt in and answer elements
const SMACK_OUTWITCHATDIV = "chatPost";  // was "chat", commentInfo
const SMACK_COMMENTTEXT = "commentText";
const SMACK_COMMENTNICK = "chatNick";
const SMACK_COMMENTAVATAR = "chatAvatarContainer";
const SMACK_OUTWITCOMMENTDIV = "comment_comment";
const SMACK_PMDIV = "messagesContainer";
const SMACK_OUTWITCAPDIV = "captchaBox";
const SMACK_OUTWITANSWERDIV = "outwitAnswer";
const SMACK_OUTWITGURUGUESSDIV = "guruMakeGuess";
const SMACK_DEALDIV = "deal";
const SMACK_OUTWITCONDIV = "outwitContainer";
const SMACK_GURUCONDIV = "guruContainer";
//needed???
const SMACK_SHOWNAMEVALUE = "showName";
const SMACK_SHOWNAMEDIV = "The Daily Smack with Smack Daddy";

const SMACK_ALERT_CUSTOM = -1;
const SMACK_ALERT_OUTWITOPTIN = 1;
const SMACK_ALERT_OUTWITVOTE = 2;
const SMACK_ALERT_GURUGUESS = 10;
const SMACK_ALERT_SMACKPOTGUESS = 20;
const SMACK_ALERT_BUYALERT = 30;
const SMACK_ALERT_GURUWHEELSPIN = 40;

//var SS_chatcss = "@namespace url(http://www.w3.org/1999/xhtml);  /* Change color of  links */ #chat div.commentText a:visited, #chat div.commentText a:link { color: #FF7800 !important; } ";

var SS_chatcss = "@namespace url(http://www.w3.org/1999/xhtml);  /* Change color of  links */ #chat div.commentText a:visited, #chat div.commentText a:link { color: #FF7800 !important; } a.swaksmackReply { color: #FF7800 !important; font-size: 11px;} a.swaksmackHighlightUser, a.swaksmackUnhighlightUser {color: #FFBC80 !important; font-size: 11px;}  ";


var SS_chatHeaderChange = false;



var SS_ggListenerAdded = false;
var SS_keywordDisplayLength = 15;

var SS_window;


var SS_dynamicKeywords = new Array();


var SS_dynamicUsernames = new Array();

var SS_colorCommentMatchArray = new Array();
var SS_ChatHeaderText = null;
var SS_UID;
var SS_ggcalc;
var SS_GGCalcWindow;

var tinyurlpreviewregex = /tinyurl\.com\/(.*)/i;

const JF_HL_replacement = "\u0009\(\[^\u0009\]*\)\u0009";
var JF_HL_repRegEx = new RegExp(JF_HL_replacement,"g");
const JF_taggedMatches = "\u0009$1\u0009";
const JF_pass2replace = "$1";

//ignore list
var JF_ignoreUserlistRegExp = null;
var JF_ignoreWordlistRegExp = null;
var JF_ignoreAttendancelistRegExp = null;

//highlight lists
var JF_keywordlistRegExp = null;
var JF_usernamelistRegExp = null;

var JF_usernamelist2RegExp = null;

var JF_usernameArray = new Array();
var JF_keywordArray = new Array();

var SwakChatThemeRegEx = new RegExp("([^,|]*),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6})","ig");
var SwakChatThemeColorsRegExStr = ",(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6})";


function SwakChatTheme() {
	this.name = null;
	this.chatBkgrd = null;
	this.chatText = null;
	this.chatNick = null;
	this.chatGuru = null;
	this.chatTime = null;
	this.chatActions = null;
	this.chatLinks = null;
	this.cBkgrd = null;
}

function buildSwakChatThemes(themeString) {
	if (themeString == null) return null;
	//var search = "([^,|]*)" + SwakChatThemeColorsRegExStr;
	//alert('search string ' + search);
	//var themeRE = new RegExp(search,"i");
	var matches = null;
	var result = new Array();
	while((matches = SwakChatThemeRegEx.exec(themeString)) != null) {   //while ((matches = oRegExp.exec(inputText)) != null)
		if (matches == null) continue;	
		//alert('matches: ' + matches);
		var chatTheme = new SwakChatTheme();
		chatTheme.name = matches[1];
		chatTheme.chatBkgrd = matches[2];
		chatTheme.chatText = matches[3];
		chatTheme.chatNick = matches[4];
		chatTheme.chatGuru = matches[5];
		chatTheme.chatTime = matches[6];
		chatTheme.chatActions = matches[7];
		chatTheme.chatLinks = matches[8];
		chatTheme.cBkgrd = matches[9];
		result.push(chatTheme);
		//alert('results array length ' + result.length);
	}
	
	return result;
}


function buildSwakChatTheme(themeName, themeString) {
	if (themeName == null || themeString == null) return null;
	if (themeString.indexOf(themeName) == -1) return null;
	var search = themeName + SwakChatThemeColorsRegExStr;
	var themeRE = new RegExp(search,i);
	var matches = themeRE.exec(themeString);
	if (matches == null) return null;
	var chatTheme = new SwakChatTheme();
	chatTheme.name = themeName;
	chatTheme.chatBkgrd = matches[1];
	chatTheme.chatText = matches[2];
	chatTheme.chatNick = matches[3];
	chatTheme.chatGuru = matches[4];
	chatTheme.chatTime = matches[5];
	chatTheme.chatActions = matches[6];
	chatTheme.chatLinks = matches[7];
	chatTheme.cBkgrd = matches[8];
	return chatTheme;
}

function buildSwakThemeString(name,chatBkgrd,chatText,chatNick,chatGuru,chatTime,chatActions,chatLinks,cBkgrd) {
	var themeString = name;
	themeString += ',';
	themeString += chatBkgrd;
	themeString += ',';
	themeString += chatText;
	themeString += ',';
	themeString += chatNick;
	themeString += ',';
	themeString += chatGuru;
	themeString += ',';
	themeString += chatTime;
	themeString += ',';
	themeString += chatActions;	
	themeString += ',';
	themeString += chatLinks;
	themeString += ',';
	themeString += cBkgrd;	
	themeString += '|';
	return themeString;	
}

function buildSwakThemeStringFromObject(chatTheme) {
	if (chatTheme == null ) return '';
	var themeString = chatTheme.name;
	themeString += ',';
	themString += chatTheme.chatBkgrd;
	themeString += ',';
	themString += chatTheme.chatText;
	themeString += ',';
	themString += chatTheme.chatNick;
	themeString += ',';
	themString += chatTheme.chatGuru;
	themeString += ',';
	themString += chatTheme.chatTime;
	themeString += ',';
	themString += chatTheme.chatActions;	
	themeString += ',';
	themString += chatTheme.chatLinks;	
	themeString += ',';
	themString += chatTheme.cBkgrd;		
	themeString += '|';
	return themeString;	
}

function checkHost(doc) {
    if (doc==null)
        return false; 
	host = doc.location.host;
	//alert(host);
	if (host == 'www.jellyfish.com' || host == 'jellyfish.com' || host==null || host=='')
	return true;
	return false;
}

function isPMArea(doc) {

	if (doc == null) doc=content.document;
	var hostPath = doc.location.pathname;
	var matches = hostPath.match("/shoppers/me/messages");
	if (matches != null) {
		return true;
	}
	return false;
}

function isSmackShopArea(doc) {
	if (doc == null) doc = content.document;
	var hostPath = doc.location.pathname;
	var matches = hostPath.match("/smacktv/channel");
	if (matches != null) {
		return true;
	}
	return false;
}

function isLRArea(doc) {
	if (doc == null) doc = content.document;
	var lrDiv = doc.getElementById('livingRoomName');
	if (lrDiv != null) return true;
	return false;
}

function chatLinkColor(doc) {
	if (doc == null) doc = content.document;
	var heads = doc.getElementsByTagName("head");
	if (heads.length > 0) {
		/*
		var node = doc.createElement("style");
		///	node.href="chrome://swaksmack/skin/swaksmack.css";
		node.innerHTML = SS_chatcss;
		node.type = "text/css";
		heads[0].appendChild(node);
		*/
		var node = doc.createElement("link");
		node.href="chrome://swaksmack/skin/swaksmack.css";
		//node.innerHTML = SS_chatcss;
		node.type = "text/css";
		node.rel="Stylesheet";
		heads[0].appendChild(node);
	}
}
//from http://robertnyman.com/js/getElementsByClassName.js
function getElementsByClassName_ORG(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

function _getElementsByXPath(expression,parent) {
	var results = [];
	var query = document.evaluate(expression, parent || window.content.document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	for (var i = 0, length = query.snapshotLength; i < length; i++)
	results.push(query.snapshotItem(i));
	return results;
};
function getElementsByClassName(className,parent) {
	var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
	return _getElementsByXPath(q,parent);
}

function buildClassNameRegex(strClassName) {
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	return oRegExp;
}

function buildSearchString(searchArray, wordBoundary) {
	if(wordBoundary == null) wordBoundary = true;
	var searchreg = null;
	if (searchArray == null || searchArray.length == 0) return '';
	for (var i=0; i<searchArray.length;i++){
		if (searchArray[i] == null || searchArray[i]== "") continue;
		if (searchreg == null) {
			var trimmed = searchArray[i].replace(/^\s+|\s+$/g, '') ;
			searchreg = SS_escapeRegExLiterals(trimmed);
			//searchreg = SS_escapeRegExLiterals(searchArray[i].trim());
			if(wordBoundary) {
				var glob = /\\\*$/.test(searchreg);
				if (!glob) {
					searchreg = '\\b'+searchreg+'\\b';
					//alert('exact match ' + searchreg);
				}
				else {
					//replace \*
					searchreg = searchreg.replace(/\\\*$/,'');
				}
			}
			if (searchreg == '')
			searchreg = null;
			continue;
		}
		var trimmed = searchArray[i].replace(/^\s+|\s+$/g, '') ;
		var str = SS_escapeRegExLiterals(trimmed);
		if(wordBoundary) {
			var glob = /\\\*$/.test(str);
			if (!glob) {
				str = '\\b' + str + '\\b';
			}
			else {
				str = str.replace(/\\\*$/,'');
			}
		}
		if (str != null && str != '')
		searchreg = searchreg + '|' + str;
	}
	return searchreg;
}

//http://4umi.com/web/javascript/array.htm#unique

function getUniqueArray(sourceArray,b) {
	var a = [], i, l = sourceArray.length;
	for( i=0; i<l; i++ ) {
		if( a.indexOf( sourceArray[i], 0, b ) < 0 ) { a.push( sourceArray[i] ); }
	}
	return a;
}


function highlightExistingComments(doc) {
	if (doc == null) return;
	var cm = swaksmack.SS_JF.getChatMonitor2(gBrowser.contentWindow);
	if (cm == null) return;
	for (var i=0;i<cm.length;i++) {
		var comment = 'comment' + cm[i];
		var chatComment = doc.getElementById(comment);
		commentColor(chatComment,doc);
	}
}



function highlightExistingUsernames(doc, username,highlightclass) {
	if (doc == null) return;
	var cm = swaksmack.SS_JF.getChatMonitor2(gBrowser.contentWindow);
	if (cm == null) return;
	for (var i=0;i<cm.length;i++) {
		var comment = 'comment' + cm[i];
		var chatComment = doc.getElementById(comment);
		//commentColor(chatComment,doc);
		updateHighlightLinks(doc,username,chatComment,highlightclass);

	}
}

function toggleHighlightedCommentDisplay(doc,hidden) {
	if (doc == null || hidden == null) return;
	var cm = swaksmack.SS_JF.getChatMonitor2(gBrowser.contentWindow);
	if (cm == null) return;
	for (var i=0;i<cm.length;i++) {
		var comment = 'comment' + cm[i];
		var chatComment = doc.getElementById(comment);
		if (hidden == true) {
			//don't hide highlighted comments
			var sunhl = chatComment.getAttribute('swaksmackusernamehighlighted');
			var skhl = chatComment.getAttribute('swaksmackkeywordhighlighted');
			if (sunhl == 'true' || skhl == 'true'){
				//alert('found comment to NOT hide');
				continue;
			}
			//chatComment.style.display='none';
			hideChatComment(chatComment, true);
		}
		else {
			hideChatComment(chatComment, false);
			//chatComment.style.display='inline';
		}
		//commentColor(chatComment,doc);

	}
}

function hideChatComment(chatComment, hide) {
	if (chatComment == null) return;
	if (hide == true) {
		chatComment.style.display='none';
	}
	else {
		chatComment.removeAttribute("style");
	}
}

function clearHighlightArrays() {
	JF_usernameArray = [];
	JF_keywordArray = [];
}

function commentEnhance(element, doc) {
	// alert(element.className + ' (cn) commentEnhance entry (id) ' +element.id);

	if (isLRArea(doc) == true && SS_getPreference(SMACK_ENABLELRHL) == false) {
		//alert('ce--lr return');
		return;
	}

	var jellyfishstrings = document.getElementById("swaksmack-strings");

	//	if (true) return;
	var commentInfo = getElementsByClassName("commentInfo",element);
	var chatNick = getElementsByClassName('chatNick',commentInfo[0]);
	var postUserName = chatNick[0].textContent;

	//var usernames =SS_getPreference(SMACK_USERNAMEHL1);

	var unindex = SS_dynamicUsernames.indexOf(postUserName);   //was SS_combinedUsernames

	var tooltip = '';
	//alert('postUserName ' + postUserName + ' unindex ' + unindex);
	var useImage = false;
	try {
		useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);
	}
	catch(x){}

	var commentText = getElementsByClassName("commentText",element);
	//	var chatPost = getElementsByClassName("chatPost",element);
	var link = doc.createElement("a");
	if (unindex<0) {
		link.className='swaksmackHighlightUser';
		if (useImage) {
			link.innerHTML="<img src=\"chrome://swaksmack/skin/icons/highlighter.png\"/>";
		}
		else {
			link.textContent='Highlight';
		}
		tooltip = jellyfishstrings.getString("highlight_tooltip");
		link.title=tooltip;

	}
	else {
		link.className='swaksmackUnhighlightUser';
		if (useImage) {
			link.innerHTML="<img src=\"chrome://swaksmack/skin/icons/unhighlighter.png\"/>"; //class=\"swaksmackUnhighlightUser\"
		}
		else {
			link.textContent='Unhighlight';
		}
		tooltip = jellyfishstrings.getString("unhighlight_tooltip");
		link.title=tooltip;

	}
	link.target='_blank';
	link.href = '#';
	try{
		commentInfo[0].insertBefore(link,commentText[0]);
	}
	catch (x) {}

	link.addEventListener('click', enhancedHighlight,false);



	//insert a space
	var txtNode = doc.createTextNode(" ");
	try{
		commentInfo[0].insertBefore(txtNode,commentText[0]);
	}
	catch (x) {}

	var replylink = doc.createElement("a");
	replylink.className='swaksmackReply';
	if (useImage) {
		replylink.innerHTML="<img src=\"chrome://swaksmack/skin/icons/user_comment.png\"/>";
	}
	else {
		replylink.textContent=' Reply';
	}
	tooltip = jellyfishstrings.getString("reply_tooltip");
	replylink.title=tooltip;

	replylink.target='_blank';
	replylink.href = '#';
	try{
		//commentInfo[0].appendChild(link);
		commentInfo[0].insertBefore(replylink,commentText[0]);
	}
	catch (x) {}

	replylink.addEventListener('click', enhancedReply,false);
	
		//add "actions..."
	
  //insert a space
	txtNode = doc.createTextNode(" ");
	try{
		commentInfo[0].insertBefore(txtNode,commentText[0]);
	}
	catch (x) {}
	
	
	var actionlink = doc.createElement("a");
	actionlink.className='swaksmackAction';
	if (useImage) {
		actionlink.innerHTML="<img src=\"chrome://swaksmack/skin/icons/user_edit.png\"/>";
	}
	else {
		actionlink.textContent=' Actions';
	}
	tooltip = 'Actions';jellyfishstrings.getString("reply_tooltip");
	actionlink.title=tooltip;

	actionlink.target='_blank';
	actionlink.href = '#';
	try{
		commentInfo[0].insertBefore(actionlink,commentText[0]);
	}
	catch (x) {}
	
	actionlink.addEventListener('click', enhancedAction,false);

	commentInfo = null;
	commentText = null;
	chatNick = null;


}

function enhancedAction(e) {
	e.stopPropagation();
	e.preventDefault();
	if (swaksmack.actionPopup == null) {
			swaksmack.actionPopup = document.getElementById('swaksmackActions');
	}

	var actions = document.getElementById('swaksmackActions');
	document.popupNode = null;
	swaksmack.postPopupNode = null;
	var useImage = false;
	try {
		useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);
	}
	catch(x){}
	try {		
		
		//check is action is using an image
		if (useImage) {
			swaksmack.postPopupNode = e.target.parentNode.parentNode;
		}
		else {
			swaksmack.postPopupNode = e.target.parentNode;
		}
		//the anchor element needs to be some XUL element---so far this works
		actions.showPopup(document.getElementById('status-bar'),e.screenX,e.screenY,"popup"); 
		//swaksmack.actionPopup.showPopup(document.getElementById('status-bar'),e.screenX,e.screenY,"popup");

//weird--this works on one machine, but on another it on workd during a dblclick
	//	actions.showPopup(document.getElementById('swaksmackActions'),e.screenX,e.screenY,"popup"); 

	}
	catch (x) {
		alert('popup error ' + x);
	}
	
	
}

function enhancedHighlight(e) {
	e.stopPropagation();
	e.preventDefault();
	//alert('enhancedHighlight');
	//check is a username is selected and find that name
	if (findUsername() == true) {
		//name found...return
		e.target.focus();
		swakClearCurrentSelection();
		return;
	}
	swakClearCurrentSelection();

	var useImage = false;
	try {
		useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);
	}
	catch(x){}
	var highlightTarget = e.target;
	if (useImage) {
		highlightTarget = e.target.parentNode;
	}

	var ci = getCommentInfo(highlightTarget);


	//alert(pn.className + ' (org) --commentInfo element ' + ci.className);
	var chatNick = getElementsByClassName('chatNick',ci);
	var username = chatNick[0].textContent;

	var cn = highlightTarget.className;
	//highlightExistingUsernames(swaksmack.SmackShopDoc,username,cn);

	highlightExistingUsernames(content.document,username,cn);

	chatNick = null;

}



function findUsername(username) {
	var selectedName = '';
	if (username == null) {
		try {
			if (gContextMenu && gContextMenu.searchSelected) 
				selectedName = gContextMenu.searchSelected();
			else
				selectedName = getBrowserSelection();
		}
		catch (x) {return false;}
		if (selectedName == null || selectedName.length == 0) {
			return false;
		}
	}
	else {
		selectedName = username;
	}
	//now search posts for name
	var cm = swaksmack.SS_JF.getChatMonitor2(gBrowser.contentWindow);
	if (cm == null) return false;
	var nameRE = new RegExp(selectedName,"i");
	//alert('selectedName nameRE ' + nameRE);
	var found = false;
	for (var i=0;i<cm.length;i++) {
		nameRE.lastIndex = 0;
		var comment = 'comment' + cm[i];
		var chatComment = swaksmack.SmackShopDoc.getElementById(comment);
		if (chatComment == null) continue;
		var chatNick = getElementsByClassName('chatNick',chatComment);
		if (chatNick == null || chatNick[0] == null) continue;
		var possibleMatch = nameRE.test(chatNick[0].textContent);
		//alert('findUsername chatNick[0] ' + chatNick[0]);
		if (possibleMatch == true) {
			//alert('found user ' + chatNick[0]);
			found = true;
			highlightUsername(chatComment,swaksmack.SmackShopDoc);
		}
	}
	//return found;
	return true;
	
}

function updateHighlightLinks(doc,username, chatComment, highlightclass) {
	//alert('UHL');
	if (doc == null|| username == null || chatComment == null || highlightclass == null) return;
	if (SS_getPreference(SMACK_GLOBAL_ENABLEHL) == false) return;


	//var ci = getElementsByClassName('commentInfo',chatComment);
	var htarget = getElementsByClassName(highlightclass,chatComment);

	var jellyfishstrings = document.getElementById("swaksmack-strings");
	var tooltip = '';
	var useImage = false;
	try {
		useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);
	}
	catch(x){}
	var highlightTarget = htarget[0];
	var chatNick = getElementsByClassName('chatNick',chatComment);
	var postusername = chatNick[0].textContent;
	//alert(postusername + ' pun, hun ' + username);
	if (username != postusername) return;

	//alert(postusername + ' pun, hun ' + username);
	var cn = highlightclass;
	if (cn == 'swaksmackHighlightUser') {
		highlightTarget.className='swaksmackUnhighlightUser';
		if (useImage) {
			highlightTarget.innerHTML="<img src=\"chrome://swaksmack/skin/icons/unhighlighter.png\"/>";
		}
		else {
			highlightTarget.textContent='Unhighlight';
		}
		tooltip = jellyfishstrings.getString("unhighlight_tooltip");
		highlightTarget.title=tooltip;
		//alert('adding user ' + username);

		var index = SS_dynamicUsernames.indexOf(username);
		if (index == -1) {
			SS_dynamicUsernames.push(username);
			clearHighlightArrays();
			//initUserNameArray(false);
		}

		if (SS_getPreference(SMACK_GLOBAL_ENABLEHL) == true) {
			//alert('call hl username');
			//org 090707-1 commentColor(chatComment,doc,true);
			highlightUsername(chatComment,doc);
		}
	}
	else if (cn == 'swaksmackUnhighlightUser'){
		highlightTarget.className='swaksmackHighlightUser';
		if (useImage) {
			highlightTarget.innerHTML="<img src=\"chrome://swaksmack/skin/icons/highlighter.png\"/>";
		}
		else {
			highlightTarget.textContent='Highlight';
		}
		tooltip = jellyfishstrings.getString("highlight_tooltip");
		highlightTarget.title=tooltip;
		//if (SS_getPreference(SMACK_GLOBAL_ENABLEHL) == true) {
			unhighlightUsername(chatComment,doc);
		//}


		var removeNameIndex = SS_dynamicUsernames.indexOf(username);
		//alert('remove name index ' + removeNameIndex);
		if (removeNameIndex != -1) {
			//highlightExistingComments(content.document,username);
			if (removeNameIndex == 0 ) {
				SS_dynamicUsernames.shift();
				clearHighlightArrays();
				//initUserNameArray(false);
			}
			else if(removeNameIndex ==SS_dynamicUsernames.length-1){
				SS_dynamicUsernames.pop();
				clearHighlightArrays();
				//initUserNameArray(false);
			}
			else {
				SS_dynamicUsernames = SS_dynamicUsernames.splice(1,removeNameIndex);
				clearHighlightArrays();
				//initUserNameArray(false);
			}
		}

	}

	chatNick = null;
}


function enhancedReply(e) {
	//alert('enhanced reply ' + e.target);
	e.stopPropagation();
	e.preventDefault();

	try {
		var useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);

		var replyTarget = e.target;
		if (useImage) {
			replyTarget = e.target.parentNode;
		}

		var ci = getCommentInfo(replyTarget);
		var chatNick = getElementsByClassName('chatNick',ci);
		var username = chatNick[0].textContent;
		var chatPrefix ='';
		if (chatNick != null && chatNick[0] != null) {
			//alert( ' reply to ' + username);
			var cpost = content.document.getElementById('comment_comment');
			var replyText = getBrowserSelection();

			if (replyText != null && replyText.length>0) {
				replyText = "\""+replyText+"\"";
			}
			else {
				replyText = '';
			}


			cpost.value = buildReply(username,replyText);
			cpost.focus();
			swakClearCurrentSelection();

		}
	}
	catch(x){}
}

function swakClearCurrentSelection() {
	try {
	var s = swaksmack.smackShopContentWindow.getSelection();
	if(s.rangeCount > 1) {
	 for(var i = 1; i < s.rangeCount; i++) {
	  s.removeRange(s.getRangeAt(i));
	 }
	}
}
catch(x) {}
}

function previewTinyURL(element, doc, turl, commentDiv) {
	//alert(' previewTinyURL ' + element.textContent);
	if (element == null || doc == null || turl == null || commentDiv == null) return;
	var commentPosts = getElementsByClassName("chatPost",commentDiv);
	var chatPost = commentPosts[0];
	var commentTexts = getElementsByClassName(SMACK_COMMENTTEXT,chatPost);

	var useImage = false;
	try {
		useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);
	}
	catch(x){}
	var jellyfishstrings = document.getElementById("swaksmack-strings");
	var tooltip = '';
	var previewlink = doc.createElement("a");
	previewlink.className = 'swaksmacktinyurlpreview';
	turl = turl.replace(/tinyurl\.com/,"preview.tinyurl.com");
	previewlink.href = turl;
	if (useImage) {
		previewlink.innerHTML="<img src=\"chrome://swaksmack/skin/icons/monitor_link.png\"/>";
	}
	else {
		previewlink.textContent = '(preview)';
	}
	tooltip = jellyfishstrings.getString("tinyurl_preview_tooltip");
	previewlink.title = tooltip;
	previewlink.rel="external";

	element.parentNode.parentNode.insertBefore(previewlink, element.parentNode.nextSibling);
	var space = doc.createTextNode(' ');
	element.parentNode.parentNode.insertBefore(space, previewlink);
}

function buildReply(username,replytext) {
	//alert('buildReply ' + username);
	if (username == null) return '';
	var prefix = SS_getPreference(SMACK_REPLYPREFIX);
	var suffix = SS_getPreference(SMACK_REPLYSUFFIX);
	var reply = prefix + username;
	if (replytext != null && replytext != '')
	reply = reply + " " + replytext + suffix + ' ';
	else
		reply = reply + suffix + ' ';
		return reply;

	}

	function highlightUsername(element, doc) {
		if (isLRArea(doc) == true && SS_getPreference(SMACK_ENABLELRHL) == false) {
			return;
		}
		var dynunoption = SS_getPreference(SMACK_HL_DYNUNOPT);
		//alert('highlightUsername dynunoption ' + dynunoption);
		var highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL1);
		var outlinePost = SS_getPreference(SMACK_OUTLINEHL1);
		var commentPosts = getElementsByClassName("chatPost",element);
		var chatPost = commentPosts[0];
		var textColor = SS_getPreference(SMACK_TCHL1);
		var bkgrdColor = SS_getPreference(SMACK_BTCHL1);
		var outlinePost = SS_getPreference(SMACK_OUTLINEHL1);
		var highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL1);
		var hlopt = "1";
		if (dynunoption == "2"){
			hlopt = "2";
			highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL2);
			outlinePost = SS_getPreference(SMACK_OUTLINEHL2);
			textColor = SS_getPreference(SMACK_TCHL2);
			bkgrdColor = SS_getPreference(SMACK_BTCHL2);
			outlinePost = SS_getPreference(SMACK_OUTLINEHL2);
			highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL2);
		}
		else if (dynunoption == "3") {
			hlopt = "3";
			highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL3);
			outlinePost = SS_getPreference(SMACK_OUTLINEHL3);
			textColor = SS_getPreference(SMACK_TCHL3);
			bkgrdColor = SS_getPreference(SMACK_BTCHL3);
			outlinePost = SS_getPreference(SMACK_OUTLINEHL3);
			highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL3);
		}
		
		
		var chatNick = getElementsByClassName(SMACK_COMMENTNICK,chatPost);

		if (highlightUsernameOnly) {
			//just highlight username
			//var bkgrdColor = SS_getPreference(SMACK_BTCHL1);
			//chatNick[0].style.background = bkgrdColor;
			//var textColor = SS_getPreference(SMACK_TCHL1);
			//chatNick[0].style.color = textColor;

			highlightBackgroundAndText(chatNick[0],bkgrdColor,textColor);

		}
		else if (!outlinePost) {
		//	var bkgrdColor = SS_getPreference(SMACK_BTCHL1);
			//chatPost.style.background = bkgrdColor;
		//	var textColor = SS_getPreference(SMACK_TCHL1);
			//chatPost.style.color = textColor;

			highlightBackgroundAndText(chatPost,bkgrdColor,textColor);
		}

		if (outlinePost == true) {
			//chatPost.style.border='3px solid ' + bkgrdColor;
			highlightOutline(chatPost,bkgrdColor);
		}

		element.setAttribute('swaksmackusernamehighlighted',true);
		element.setAttribute('swaksmackhlcss',hlopt);
		if (swaksmack.smackCommentsHidden == true) {
			//alert('hide uhl post');
			hideChatComment(element, false);
		}
	}

	function unhighlightUsername(element, doc) {
		if (isLRArea(doc) == true && SS_getPreference(SMACK_ENABLELRHL) == false) {
			return;
		}
		//alert('unhighlight');
		var highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL1);
		var outlinePost = SS_getPreference(SMACK_OUTLINEHL1);
		var commentPosts = getElementsByClassName("chatPost",element);
		var chatPost = commentPosts[0];
		chatPost.style.border='none';
		chatPost.style.background = 'inherit';
		chatPost.style.color = 'inherit';

		var chatNick = getElementsByClassName(SMACK_COMMENTNICK,chatPost);

		highlightBackgroundAndText(chatNick[0],null,null);
		
//		chatNick[0].style.background = null;
//		chatNick[0].style.color = null;
		
	//	highlightBackgroundAndText(chatNick[0],'inherit','inherit');

		element.setAttribute('swaksmackusernamehighlighted',false);
		element.setAttribute('swaksmackhlcss','');
		if (swaksmack.smackCommentsHidden == true) {
			hideChatComment(element, true);
		}
	}
	
	function buildUsernameRegex(usernames,chatwildcardmatch,dynamicUNArray) {
		if ((usernames == null || usernames.length ==0) && (dynamicUNArray == null || dynamicUNArray.length == 0)) return null;
		var temp = usernames.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(',');
		temp = buildSearchString(temp, chatwildcardmatch);
		if (dynamicUNArray != null && dynamicUNArray.length >0) {
			var dwords = buildSearchString(dynamicUNArray, chatwildcardmatch);
			temp = temp + '|' + dwords;
		}
		
		
		temp = temp.replace(/(\|$)|(,$)/g,'');
		temp = '(' + temp + ')';
		var re = null;
		re = new RegExp(temp,"ig");  //was ig
		return re;
	}
	
	function buildKeywordRegex(keywords,chatwildcardmatch,ignoreCase,dynamicKWArray) {
		if ((keywords == null || keywords.length ==0) && (dynamicKWArray == null || dynamicKWArray.length == 0)) return null;
		var temp = keywords.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(',');
		//alert('buildKeywordRegex ' + chatwildcardmatch);
		temp = buildSearchString(temp, chatwildcardmatch);
		if (dynamicKWArray != null && dynamicKWArray.length >0) {
			var dwords = buildSearchString(dynamicKWArray, true);  // chatwildcardmatch
			temp = temp + '|' + dwords;
		}
		
		
		temp = temp.replace(/(\|$)|(,$)/g,'');
		temp = '(' + temp + ')';
		var re = null;
		if(ignoreCase == true) re = new RegExp(temp,"ig");  //was ig
		else re = new RegExp(temp,"g"); //was "g"
		return re;
	}
	
	function REMOVEQ_checkHighlightMatch(comment,username,usernamesRE,keywordsRE,highlightKeywordsOnly) {
		if (comment == null || comment == '') return 0;
		var matchvalue = 0;
		
		var kwmatch = false;
		if (keywordsRE != null) {
			kwmatch = colorByComment(comment,keywordsRE, highlightKeywordsOnly);
		}
		var unmatch = false;
		if (username != null && usernamesRE != null) {
			unmatch = colorByUsername(username,usernamesRE);
		}
		
		if (kwatch == true && unmatch == false) {
			matchvalue = 10;
		}		
		else if (kwatch == false && unmatch == true) {
			matchvalue = 20;
		}
		else if (kwatch == true && unmatch == true) {
			matchvalue = 30;
		}
		
		
		return matchvalue;
	}
	
	function updateChatHighlighting(doc) {
		//alert('updateChatHighlighting');
		var keywords = SS_getPreference(SMACK_KEYWORDHL1);
		var usernames =SS_getPreference(SMACK_USERNAMEHL1);
		var chatwildcardmatch = SS_getPreference(SMACK_CHATWILDCARD1);
		var ignoreCase = SS_getPreference(SMACK_IGNORECASEHL);
		var dynunoption = SS_getPreference(SMACK_HL_DYNUNOPT);
		var dynkwoption = SS_getPreference(SMACK_HL_DYNKWOPT);

		if(JF_keywordArray == null || JF_keywordArray.length == 0) {
			if(dynkwoption == "1") {
				JF_keywordArray[0] = buildKeywordRegex(keywords,chatwildcardmatch,ignoreCase,SS_dynamicKeywords);
			}
			else {
				JF_keywordArray[0] = buildKeywordRegex(keywords,chatwildcardmatch,ignoreCase,null);
			}
			var bccss = SS_getPreference(SMACK_BTCHL1);
			var tccss = SS_getPreference(SMACK_TCHL1);
			var swackcss = "swakhl1css";
			//alert("1. insertPostInfoCSS");
			insertPostInfoCSS(doc,"1",swackcss,tccss,bccss);
			

			//alert('JF_keywordArray[0] ' + JF_keywordArray[0]);
			//JF_keywordArray[0] = 	JF_keywordlistRegExp;
			
			chatwildcardmatch = SS_getPreference(SMACK_CHATWILDCARD2);
			var khl2 = SS_getPreference(SMACK_KEYWORDHL2);
			//ignoreCase = SS_getPreference(SMACK_IGNORECASEHL2);
			if(dynkwoption == "2") {
				JF_keywordArray[1] = buildKeywordRegex(khl2,chatwildcardmatch,ignoreCase,SS_dynamicKeywords);
				//alert('updateChatHighlighting1 dyna ' + JF_keywordArray[1]);
			}
			else {
				
				JF_keywordArray[1] = buildKeywordRegex(khl2,chatwildcardmatch,ignoreCase,null);
				//alert('updateChatHighlighting1 ' + JF_keywordArray[1]);
			}
			
			bccss = SS_getPreference(SMACK_BTCHL2);
			tccss = SS_getPreference(SMACK_TCHL2);
			swackcss = "swakhl2css";
			insertPostInfoCSS(doc,"2",swackcss,tccss,bccss);
			
			
			chatwildcardmatch = SS_getPreference(SMACK_CHATWILDCARD3);
			//alert("chatwildcardmatch3 " + chatwildcardmatch);
			var khl3 = SS_getPreference(SMACK_KEYWORDHL3);
			//ignoreCase = SS_getPreference(SMACK_IGNORECASEHL3);
			if(dynkwoption == "3") {
				JF_keywordArray[2] = buildKeywordRegex(khl3,chatwildcardmatch,ignoreCase,SS_dynamicKeywords);
			}
			else {
				JF_keywordArray[2] = buildKeywordRegex(khl3,chatwildcardmatch,ignoreCase,null);
			}
			
			bccss = SS_getPreference(SMACK_BTCHL3);
			tccss = SS_getPreference(SMACK_TCHL3);
			swackcss = "swakhl3css";
			insertPostInfoCSS(doc,"3",swackcss,tccss,bccss);
			
			//alert("JF_keywordArray[2] " + JF_keywordArray[2]);
		}

		if (JF_usernameArray == null || JF_usernameArray.length == 0) {
			
			//alert('JF_usernameArray length is 0');
			chatwildcardmatch = SS_getPreference(SMACK_CHATWILDCARD1);
			if(dynunoption == "1") {
				//alert("dyn un option 1");
				JF_usernameArray[0] = buildUsernameRegex(usernames,chatwildcardmatch,SS_dynamicUsernames);
			}
			else {
				JF_usernameArray[0] = buildUsernameRegex(usernames,chatwildcardmatch,null);
			}
			//alert('JF_usernameArray[0] ' + JF_usernameArray[0]);
			//JF_usernameArray[0] = JF_usernamelistRegExp;
			
			var uhl2 = SS_getPreference(SMACK_USERNAMEHL2);	
			chatwildcardmatch = SS_getPreference(SMACK_CHATWILDCARD2);
			if(dynunoption == "2") {
				JF_usernameArray[1] = buildUsernameRegex(uhl2,chatwildcardmatch,SS_dynamicUsernames);
			}
			else {
				JF_usernameArray[1] = buildUsernameRegex(uhl2,chatwildcardmatch,null);
			}
			
			var uhl3 = SS_getPreference(SMACK_USERNAMEHL3);	
			chatwildcardmatch = SS_getPreference(SMACK_CHATWILDCARD3);
			if(dynunoption == "3") {
				//alert("dyn un option 3");
				JF_usernameArray[2] = buildUsernameRegex(uhl3,chatwildcardmatch,SS_dynamicUsernames);
			}
			else {
				JF_usernameArray[2] = buildUsernameRegex(uhl3,chatwildcardmatch,null);
			}
			
		}
		
		
	}

	function commentColor(element, doc) {
		if (isLRArea(doc) == true && SS_getPreference(SMACK_ENABLELRHL) == false) {
			return;
		}

		element.setAttribute('swaksmackusernamehighlighted',false);
		element.setAttribute('swaksmackkeywordhighlighted',false);

		
		var ignorePostsEnabled= SS_getPreference(SMACK_ENABLEIGNORE1);
		var ignorelist =SS_getPreference(SMACK_IGNORELIST1);
		var ignorelist2 = SS_getPreference(SMACK_IGNORELIST2);
		var ignorelistattend = SS_getPreference(SMACK_IGNORELISTATTEND);

		var blockwildcardmatch = SS_getPreference(SMACK_BLOCKWILDCARD);
		var ignoreSelfPosts = SS_getPreference(SMACK_IGNORESPHL);
		var hideAvatar = SS_getPreference(SMACK_ENHANCEHIDEAVATARS);
		var highlightJFEmployees = SS_getPreference(SMACK_HL_ENABLEJFEMPLOYEE);

		var userMuted = false;

		var commentPosts = getElementsByClassName("chatPost",element);
		var chatPost = commentPosts[0];
		if (chatPost == null)  {
			//user may be muted
			commentPosts = getElementsByClassName("chatPostMuted",element);
			chatPost = commentPosts[0];
			if (chatPost != null) {
				userMuted = true;
			}
			else {
				//chat post not found at all
				return;
			}
		}

		var commentTexts = getElementsByClassName(SMACK_COMMENTTEXT,chatPost);
		var chatNick = getElementsByClassName(SMACK_COMMENTNICK,chatPost);  //"chatNick" "chatAvatarContainer"
		if (commentTexts == null || chatNick == null) return;

		if (hideAvatar) {
			var chatAvatar = getElementsByClassName('chatAvatar',chatPost);  //"chatNick" "chatAvatarContainer"
			chatAvatar[0].style.display='none';
		}


		if (ignoreSelfPosts) {
			var nickname = swaksmack.SS_JF.getNickName();
			//	alert(chatNick[0].textContent + ' chatnick, ignore self nn ' + nickname);
			if (chatNick[0].textContent == nickname) return;
		}

		if (ignorePostsEnabled) {
			//check post against ignore list
			if (ignorelist != null && ignorelist != "") {
				if (JF_ignoreUserlistRegExp == null) {
					ignorelist = ignorelist.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(','); // Allow for spaces in usernames
					ignorelist = buildSearchString(ignorelist,blockwildcardmatch);
					//ending with a | or , can be bad
					ignorelist = ignorelist.replace(/(\|$)|(,$)/,'');

					JF_ignoreUserlistRegExp = new RegExp(ignorelist,"ig");
				}

				//alert(usernames);
				//var ignorelistRegExp = new RegExp(ignorelist,"ig");
				if (JF_ignoreUserlistRegExp != null) {
					JF_ignoreUserlistRegExp.lastIndex = 0;
					var ignoreListMatch = isUsernameMatch(chatNick[0],JF_ignoreUserlistRegExp);
					if (ignoreListMatch) {
						var funMode= SS_getPreference(SMACK_FUNIGNORE1);
						if (funMode == true) {
							var rn = SS_getRandomNumber(20);
							var funMsg = '';
							try {
								funMsg = SS_getStringTableText("ignore_fun"+rn);
							}
							catch(x) {}
							commentTexts[0].textContent = funMsg;
						}
						else {
							element.style.display='none';
						}
						return;
					}
				}
			}

			if (ignorelist2 != null && ignorelist2 != "") {
				if (JF_ignoreWordlistRegExp == null) {
					ignorelist2 = ignorelist2.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(','); // Allow for spaces in usernames
					ignorelist2 = buildSearchString(ignorelist2,blockwildcardmatch);
					//ending with a | or , can be bad
					ignorelist2 = ignorelist2.replace(/(\|$)|(,$)/,'');
					//alert(usernames);
					JF_ignoreWordlistRegExp = new RegExp(ignorelist2,"ig");
				}

				if (JF_ignoreWordlistRegExp != null) {
					var it = commentTexts[0].textContent;
					JF_ignoreWordlistRegExp.lastIndex = 0;
					var ignoreListMatch = JF_ignoreWordlistRegExp.test(it);
					//var ignoreListMatch = isUsernameMatch(chatNick[0],ignorelistRegExp);
					if (ignoreListMatch) {
						//alert('ignoring post based on keyword');
						//chatPost.style.display='none';
						element.style.display='none';
						return;
					}
				}
			}
			if (ignorelistattend != null && ignorelistattend != "") {
				if (JF_ignoreAttendancelistRegExp == null) {
					//alert(' attendignorelistupdate ' + JF_ignoreAttendancelistRegExp);
					ignorelistattend = ignorelistattend.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(','); // Allow for spaces in usernames
					ignorelistattend = buildSearchString(ignorelistattend, false);
					//ending with a | or , can be bad
					ignorelistattend = ignorelistattend.replace(/(\|$)|(,$)/,'');
					//allow for leading and trailing white space
					ignorelistattend = "^\\s*(" +ignorelistattend +")\\s*$";
					JF_ignoreAttendancelistRegExp = new RegExp(ignorelistattend,"ig");
				}
				if ( JF_ignoreAttendancelistRegExp != null) {
					JF_ignoreAttendancelistRegExp.lastIndex = 0;
					//alert('ignorelistRegExp ' + ignorelistRegExp);
					var it = commentTexts[0].textContent;
					var ignoreListMatch = JF_ignoreAttendancelistRegExp.test(it);
					//var ignoreListMatch = isUsernameMatch(chatNick[0],ignorelistRegExp);
					if (ignoreListMatch) {
						//alert('ignoring attendance post ' + it);
						//chatPost.style.display='none';
						element.style.display='none';
						return;
					}
				}
			}
		}
		
		var filterAllCaps = SS_getPreference(SMACK_ENABLECAPSUPRESSION);
		if (filterAllCaps == true) {
			var newtext = swakReplaceAllCaps(commentTexts[0].textContent);
			if (newtext != null) {
				//alert('All CAPS replaced for ' + commentTexts[0].textContent);
				commentTexts[0].textContent = newtext;
			}
		}
		
		updateChatHighlighting(doc);
		
		

		var chatRegExp = null;


				searchFound = false;

				var keywordMatch = false;
				var userNameMatch = false;
				var employeeMatch = false;
				var highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL1);
				var highlightKeywordsOnly = SS_getPreference(SMACK_WORDONLYHL1);
				var outlinePost = SS_getPreference(SMACK_OUTLINEHL1);
				var underlineMatch = SS_getPreference(SMACK_UNDERLINEHL1);
				var jfemployeeopt = parseInt(SS_getPreference(SMACK_HL_JFEMPLOYEEOPT));
				jfemployeeopt = jfemployeeopt-1;
				var hlMatchFound = false;
				var hlenabled = true;
				
				for (var i=0;i<3;i++) {
					if (JF_keywordArray[i] == null && JF_usernameArray[i] == null && highlightJFEmployees == false) continue;
					
					var bkgrdColor = null;
					var textColor = null;
					if (i == 0) {
						hlenabled = SS_getPreference(SMACK_ENABLEHL1);
						if (hlenabled == false) continue;
						bkgrdColor = SS_getPreference(SMACK_BTCHL1);
						textColor = SS_getPreference(SMACK_TCHL1);
						outlinePost = SS_getPreference(SMACK_OUTLINEHL1);
						highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL1);
						underlineMatch = SS_getPreference(SMACK_UNDERLINEHL1);
						highlightKeywordsOnly = SS_getPreference(SMACK_WORDONLYHL1);
					}
					else if (i == 1) {
						hlenabled = SS_getPreference(SMACK_ENABLEHL2);
						if (hlenabled == false) continue;
						bkgrdColor = SS_getPreference(SMACK_BTCHL2);
						textColor = SS_getPreference(SMACK_TCHL2);
						outlinePost = SS_getPreference(SMACK_OUTLINEHL2);
						highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL2);
						underlineMatch = SS_getPreference(SMACK_UNDERLINEHL2);
						highlightKeywordsOnly = SS_getPreference(SMACK_WORDONLYHL2);
					}
					else if (i == 2) {
						hlenabled = SS_getPreference(SMACK_ENABLEHL3);
						if (hlenabled == false) continue;
						bkgrdColor = SS_getPreference(SMACK_BTCHL3);
						textColor = SS_getPreference(SMACK_TCHL3);
						outlinePost = SS_getPreference(SMACK_OUTLINEHL3);
						highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL3);
						underlineMatch = SS_getPreference(SMACK_UNDERLINEHL3);
						highlightKeywordsOnly = SS_getPreference(SMACK_WORDONLYHL3);
					}
				
				
				if (JF_keywordArray[i] != null) {
					JF_keywordArray[i].lastIndex = 0;
					keywordMatch = colorByComment(commentTexts[0],JF_keywordArray[i], highlightKeywordsOnly,underlineMatch,textColor,bkgrdColor);
				//ad a tag to indicate that post has been highlighted
				if (keywordMatch == true) {
					hlMatchFound = true;
					var hlopt = i+1;
					element.setAttribute('swaksmackkeywordhighlighted',true);
					element.setAttribute('swaksmackhlcss',hlopt);
				}
				
				if (keywordMatch == true && highlightKeywordsOnly == false && !outlinePost) {
					//var bkgrdColor = SS_getPreference(SMACK_BTCHL1);
					//var textColor = SS_getPreference(SMACK_TCHL1);

					highlightBackgroundAndText(chatPost,bkgrdColor,textColor);

					//updateStatusbarKeyword(5);
					break;
				}
				if (keywordMatch == true && outlinePost) {
						highlightOutline(chatPost,bkgrdColor);
						break;
				}
				
			}//null check
					
					if (JF_usernameArray[i] != null) {
						JF_usernameArray[i].lastIndex = 0;
						userNameMatch = colorByUsername(chatNick[0],JF_usernameArray[i]); //
						
						if (userNameMatch) {
							hlMatchFound = true;
							element.setAttribute('swaksmackusernamehighlighted',true);
							var hlopt = i+1;
							element.setAttribute('swaksmackhlcss',hlopt);
							if (highlightUsernameOnly) {
								//just highlight username	
								highlightBackgroundAndText(chatNick[0],bkgrdColor,textColor);
							}
							else if (!outlinePost) {	
								highlightBackgroundAndText(chatPost,bkgrdColor,textColor);
							}
							if (outlinePost) {
		
								highlightOutline(chatPost,bkgrdColor);
							}
							//match found break
							break;
						}		
					}


			
	
					if (hlMatchFound == false && highlightJFEmployees == true && i == jfemployeeopt) {
						//alert('search for JM eployee');
						employeeMatch = false;
						employeeMatch = isJFEmployee(element,doc);
					
						if (employeeMatch == true) {
							//alert('JF employee found');
							var hlopt = i+1;
							element.setAttribute('swaksmackusernamehighlighted',true);
							element.setAttribute('swaksmackhlcss',hlopt);
							if (highlightUsernameOnly) {
								//just highlight username		
								highlightBackgroundAndText(chatNick[0],bkgrdColor,textColor);
							}
							else if (!outlinePost) {
		
								highlightBackgroundAndText(chatPost,bkgrdColor,textColor);
							}
							if (outlinePost) {		
								highlightOutline(chatPost,bkgrdColor);
							}
							//match found break
							break;
						}
					}
	
				
			}//end for
			
				if (swaksmack.smackCommentsHidden == true && hlMatchFound == false) {
					hideChatComment(element, true);
				}
				else {
					hideChatComment(element, false);
				}
			
			  if (hlMatchFound == true) {
			  	updateStatusbarKeyword(5);
			  }
			}
			
			function insertPostInfoCSS(doc,hlopt,cssid,textColor,bkColor) {
				if (doc == null) return;
				var heads = doc.getElementsByTagName("head");
				if (heads.length > 0) {
						var swakcss = doc.getElementById(cssid);
						//alert(cssid + ",cssid insertPostInfoCSS swakcss " + swakcss);
						if (swakcss != null) {
							heads[0].removeChild(swakcss);
							//alert('remove existing swak style');
						}
						if ((hlopt == "1" && SS_getPreference(SMACK_CHATINFOHL1) == true) ||
							(hlopt == "2" && SS_getPreference(SMACK_CHATINFOHL2) == true) ||
							(hlopt == "3" && SS_getPreference(SMACK_CHATINFOHL3) == true)) {
				
							var node = doc.createElement("style");
							node.id=cssid;
							
    					var chatcss = buildPostInfoCSS(hlopt,textColor,bkColor);
							//var chatcss = buildPostInfoCSS(hlopt,bkColor,textColor);
							node.innerHTML = chatcss;
							node.type = "text/css";
							heads[0].appendChild(node);
							//alert('swakcss added for ' + cssid);
						}

					}
			}
			
			function buildPostInfoCSS(hlopt,textColor,bkColor) {
				//var css = "#chat > [swaksmackhlcss=\"" + hlopt+"\"] a.chatNick, #chat > [swaksmackhlcss=\"" + hlopt+"\"] span.chatTime, #chat > [swaksmackhlcss=\"" + hlopt+"\"] span.chatGuru, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.chatMute, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.swaksmackReply, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.swaksmackUnhighlightUser, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.swaksmackHighlightUser{color: " + textColor + "; background: " + bkColor+ "; font-size: 11px;}";
				var css = "#chat > [swaksmackhlcss=\"" + hlopt+"\"] a.chatNick, #chat > [swaksmackhlcss=\"" + hlopt+"\"] span.chatTime, #chat > [swaksmackhlcss=\"" + hlopt+"\"] span.chatGuru, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.chatMute, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.swaksmackReply, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.swaksmackUnhighlightUser, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.swaksmackHighlightUser, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.swaksmackAction {color: " + textColor + " ! important; font-size: 11px;}";
				return css;
			}
			
			function updateChatThemeCSS(doc) {
				//alert('updateChatThemeCSS');
				//return;
				if (doc == null) return;
				var heads = doc.getElementsByTagName("head");
				var enabled = SS_getPreference(SMACK_THEME_ENABLE);
				if (heads.length > 0) {
					
					var swakthemecss = doc.getElementById('swakchattheme');
					//alert(cssid + ",cssid insertPostInfoCSS swakcss " + swakcss);
					if (swakthemecss != null) {
						heads[0].removeChild(swakthemecss);
						//alert('remove existing swak style');
					}
					if (enabled == false) {	
						return;
					}
					
					var textColor = SS_getPreference(SMACK_THEME_CHATTC);
					var bkColor = SS_getPreference(SMACK_THEME_CHATBTC);
					var chatNick = SS_getPreference(SMACK_THEME_CHATNICK);
					var chatTime = SS_getPreference(SMACK_THEME_CHATTIME); 
					var chatGuru = SS_getPreference(SMACK_THEME_CHATGURU); 
					var chatActions = SS_getPreference(SMACK_THEME_CHATACTIONS);
					var chatLinks = SS_getPreference(SMACK_THEME_CHATLINKS);
					var cBkgrd = SS_getPreference(SMACK_THEME_BKGRD);
					
					var node = doc.createElement("style");
					node.id='swakchattheme';
					
//093007					var css = "#rightPanel, #leftPanel, #chat, #chatContainer { background: " + cBkgrd + ";} #chat a.chatNick { color: " + chatNick + ";} #chat .commentFloatContainer {color: " + textColor + "; background: " + bkColor+ ";} #chat div.chatPost {color: " + textColor + ";} #chat a.chatMute, #chat a.swaksmackHighlightUser, #chat a.swaksmackUnhighlightUser, #chat a.swaksmackReply { color: " + chatActions + ";} #chat span.chatTime { color: " + chatTime + ";} #chat span.chatGuru { color: " + chatGuru + ";} #chat div.commentText a:visited, #chat div.commentText a:link { color: " + chatLinks + ";}";
//093007 var css = "#rightPanel, #leftPanel, #chat, #chatContainer { background: " + cBkgrd + ";} #chat a.chatNick { color: " + chatNick + ";} #chat .commentFloatContainer {color: " + textColor + "; background: " + bkColor+ ";} #chat div.chatPost {color: " + textColor + ";} #chat a.chatMute, #chat a.swaksmackHighlightUser, #chat a.swaksmackUnhighlightUser, #chat a.swaksmackReply { color: " + chatActions + ";} #chat span.chatTime { color: " + chatTime + ";} #chat span.chatGuru { color: " + chatGuru + ";} #chat div.commentText a:visited, #chat div.commentText a:link { color: " + chatLinks + ";}";
					var css = "#rightPanel, #leftPanel, #chat, #chatContainer { background: " + cBkgrd + ";} #chat div.chatPost:not(.moderator) a.chatNick { color: " + chatNick + ";} #chat .commentFloatContainer {color: " + textColor + "; background: " + bkColor+ ";} #chat div.chatPost:not(.moderator) {color: " + textColor + ";} #chat div.chatPost:not(.moderator) a.chatMute, #chat div.chatPost:not(.moderator) a.swaksmackHighlightUser, #chat div.chatPost:not(.moderator) a.swaksmackUnhighlightUser, div.chatPost:not(.moderator) a.swaksmackReply, #chat div.chatPost:not(.moderator) a.swaksmackAction { color: " + chatActions + ";} #chat div.chatPost:not(.moderator) span.chatTime { color: " + chatTime + ";} #chat div.chatPost:not(.moderator) span.chatGuru { color: " + chatGuru + ";} #chat div.commentText a:visited, #chat div.commentText a:link { color: " + chatLinks + ";} #chat div.administrator, #chat div.administrator a.swaksmackReply, #chat div.administrator a.swaksmackHighlightUser, #chat div.administrator a.swaksmackUnhighlightUser, #chat div.administrator a.swaksmackAction {color: " + "#FFFFFF ! important" + ";} #chat .administrator a.chatNick {color: " + "#021931 ! important" + ";} #chat .administrator .chatTime {color: " + "#7AFFCF ! important" + ";}";

					node.innerHTML = css;
					node.type = "text/css";
					heads[0].appendChild(node);
				}
			}

			function highlightOutline(element,bColor) {
				element.style.border='3px solid ' + bColor;
			}

			function highlightBackgroundAndText(element,bColor,fColor) {
				element.style.background = bColor;
				element.style.color = fColor;
			}

			function updateStatusbarKeyword(c) {
				if (swaksmack.SS_SBM == null) {
					return;
				}
				swaksmack.SS_SBM.flashKeywordButton(c);
			}

			function colorByComment(element, oRegExp, highlightKeywords, underlineMatch,textColor,bkgrdColor) {
				if (element == null || oRegExp == null) return false;
				if (highlightKeywords == null) highlightKeywords = false;
				//var underlineMatch = SS_getPreference(SMACK_UNDERLINEHL1);
				var matches;
				var inputText = element.textContent;

				var matchFound = false;

				//fix href links and so that we don't try to color/underline--will break link
				var badToColor = element.getElementsByTagName("a");

				//alert('regex ' + oRegExp);
				while ((matches = oRegExp.exec(inputText)) != null) {

					matchFound = true;
					if (underlineMatch == false && highlightKeywords == false) break;
					//for now don't attempt to color/underline as the innerhtml replace will destroy the hrefs
					if (badToColor != null && badToColor[0] !=null) break;


					var text = matches[0];

					var lastKWMatchIndex = SS_colorCommentMatchArray.indexOf(text);
					if (lastKWMatchIndex != -1) {
						continue;

					}
					//alert(oRegExp + ' (regex) matches: ' + matches);
					//alert('matched regex ' + oRegExp);

					SS_colorCommentMatchArray.push(text);
					var regextext = SS_escapeRegExLiterals(text);


					//create a group that will define $1 in the regex
					regextext = '(' +regextext + ')';

					//need to build a new regex for the matched text since multiple words in the text may match
					var mRegExp = new RegExp(regextext,"g");
					//alert(mRegExp + ' mRegExp');


					//tag the found keyword(s) by wrapping them in some char we hope we never seen in a chat post
					//var taggedMatches = "\u0009$1\u0009";
					element.textContent = element.textContent.replace(mRegExp, JF_taggedMatches);

				}

				//now replace the tagged matched words for underlined/highlighted words
				if (matchFound && (underlineMatch || highlightKeywords)) {
					// <([^>]*)>

					var pass2replace = "$1";
					if (underlineMatch == true) {
						pass2replace = SS_ulreplacement;
					}

					if (highlightKeywords == true) {
						//pass2replace = '<span style=\"color:' + SS_getPreference(SMACK_TCHL1) +';background:' + SS_getPreference(SMACK_BTCHL1) + '\">' + pass2replace + '</span>';
						pass2replace = '<span style=\"color:' + textColor +';background:' + bkgrdColor + '\">' + pass2replace + '</span>';
					}

					//replace all the tagged words in one replace of the innerhtml
					element.innerHTML = element.innerHTML.replace(JF_HL_repRegEx, pass2replace);

				}

				SS_colorCommentMatchArray = [];
				return matchFound;

			}

			function isUsernameMatch(element, oRegExp) {
				if (element == null || oRegExp == null) return false;
				var matchFound = false;
				var matches = oRegExp.exec(element.textContent);
				if (matches != null) {
					matchFound = true;
				}
				return matchFound;
			}

			function isJFEmployee(commentDiv, doc) {
				//employee badge info: <div class="largeBadge"><img alt="JF Employee" src="/img/ss/1184790884_employee.gif"/></div>
				var largeBadge = getElementsByClassName("largeBadge",commentDiv);
				if (largeBadge == null || largeBadge[0] == null) return false;
				var imgs = largeBadge[0].getElementsByTagName("img");
				var found = false;
				for (var i=0;i<imgs.length;i++) {
					var alt = imgs[i].alt;
					if (alt == 'JF Employee') {
						found = true;
						break;
					}
				}
				return found;
			}

			function processSmackHero(commentDiv, doc) {
				if (commentDiv == null || doc == null) return;
				var largeBadge = getElementsByClassName("largeBadge",commentDiv);
				if (largeBadge == null || largeBadge[0] == null) return;
				var imgs = largeBadge[0].getElementsByTagName("img");
				var shimg = null;
				for (var i=0;i<imgs.length;i++) {
					var alt = imgs[i].alt;
					if (alt == 'Smack Hero') {
						shimg = imgs[i];
						break;
					}
				}
				if (shimg == null) {
					return;
				}

				var link = doc.createElement("a");
				link.href = 'http://smackshopping.com';
				link.rel="external";
				var tooltip = '';
				var jellyfishstrings = document.getElementById("swaksmack-strings");
				tooltip = jellyfishstrings.getString("smackhero_link_tooltip");
				link.title=tooltip;
				shimg.parentNode.insertBefore(link, shimg);
				link.appendChild(shimg); // TEXT TO LINK

			}

			function colorByUsername(element, oRegExp) {
				if (element == null || oRegExp == null) return false;
				var matchFound = false;
				var matches = oRegExp.exec(element.textContent);
				if (matches != null) {
					matchFound = true;
					// draws box around username element.style.border='2px solid #ccc';
				}
				return matchFound;
			}

			function executePMLink(commentDiv, doc) {
				if (doc == null) doc = content.document;
				var chatDiv = doc.getElementById(commentDiv);
				var elements = doc.evaluate(".//text()", chatDiv, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
				if (elements == null) return;
				for (var i = 0; i < elements.snapshotLength; i++) textToLink(elements.snapshotItem(i), doc);
			}

			function execute(commentDiv, bool_highlight, doc)
			{
				//alert('execute ' +commentDiv.className);
				if (doc == null) return;
				if (commentDiv == null) return;
				if (commentDiv.id == null || commentDiv == 'undefined') return;
				if (bool_highlight == null) bool_highlight = true;

				var elements = doc.evaluate(".//text()", commentDiv, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
				for (var ii = 0; ii < elements.snapshotLength; ii++) textToLink(elements.snapshotItem(ii), doc,commentDiv);

				if (SS_getPreference(SMACK_ENHANCEDCHATUI) == true) {
					commentEnhance(commentDiv,doc);
					processSmackHero(commentDiv,doc);
				}

				if (bool_highlight == true && SS_getPreference(SMACK_GLOBAL_ENABLEHL) == true) {
					commentColor(commentDiv,doc);
				}
				
				externalLinks(commentDiv);




			}

			function textToLink(element, doc, commentDiv)
			{
				if (element.parentNode.tagName.match(SS_illegal)) return;
				var generousMatch = SS_getPreference(SMACK_EASYURL);
				var matches = element.nodeValue.match(SS_uri);
				if (matches != null) {
					var text = matches[0];
					var index = element.nodeValue.indexOf(text);
					if (index == 0)
					{
						if (element.nodeValue.length > text.length) textToLink(element.splitText(text.length), doc, commentDiv);
						var link = doc.createElement("a");
						//TEST for fixing link ref that have puncuation on the end
						var newurl = element.nodeValue.replace(/([\.!,;:\*()]*)$/i,'');
						newurl = newurl.replace(/[a-z0-9]*\.{2,}/,'');
						link.href = newurl;

						//_TEST
						///073107 link.href = element.nodeValue;
						link.rel="external";
						element.parentNode.insertBefore(link, element);
						link.appendChild(element); // TEXT TO LINK
						if (SS_getPreference(SMACK_TINYURLPREVIEW) && tinyurlpreviewregex.test(newurl)) {
							var tufound = tinyurlpreviewregex.test(newurl);
							previewTinyURL(element, doc, newurl, commentDiv);
						}
						slimFastUrl(element);
					}
					else textToLink(element.splitText(index), doc, commentDiv);
					}
					else if (generousMatch == true){
						matches = element.nodeValue.match(SS_uri2);
						if (matches != null) {
							var text = matches[0];
							var emailFound = false;
							if (text.indexOf("@") != -1) emailFound = true;
							var index = element.nodeValue.indexOf(text);
							if (index == 0)
							{
								if (element.nodeValue.length > text.length) textToLink(element.splitText(text.length), doc, commentDiv);
								var link = doc.createElement("a");
								var newurl = element.nodeValue.replace(/^([\.!,;:\*()]*)/i,'');
								newurl = newurl.replace(/[a-z0-9]*\.{2,}/,'');
								//link.href = 'http://'+element.nodeValue;
								link.href = 'http://'+ newurl;
								if (emailFound == true) {
									link.href = 'mailto:'+newurl;
								}
								link.rel="external";
								element.parentNode.insertBefore(link, element);
								link.appendChild(element); // TEXT TO LINK

								if (SS_getPreference(SMACK_TINYURLPREVIEW) && tinyurlpreviewregex.test(newurl)) {
									previewTinyURL(element, doc, link.href, commentDiv);
								}
								slimFastUrl(element);
							}
							else textToLink(element.splitText(index), doc, commentDiv);
							}
						}

					}

					function slimFastUrl(element){
						if(element == null) return;
						var trimUrlLength = SS_getPreference(SMACK_MAXURL);
						if (trimUrlLength == false) return;
						var maxUrlLength = SS_getPreference(SMACK_MAXLENGTH);
						if (maxUrlLength <=0) {
							var jellyfishstrings = document.getElementById("swaksmack-strings");
							var error = jellyfishstrings.getString("maxUrlLengthError1");
							alert(error);
							//var defPrefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService.getDefaultBranch());
							var defPrefs = SS_prefs.getDefaultBranch('extensions.swaksmack.');
							maxUrlLength = defPrefs.getIntPref('maxurllength_intpref');
							SS_prefs.setIntPref(SMACK_MAXLENGTH, maxUrlLength);
						}
						var clippedUrlEnd=SS_getPreference(SMACK_TRUNCURL);
						if (maxUrlLength > 0 && element.nodeValue.length > maxUrlLength){
							var replacelength = element.nodeValue.length;
							var l1 = clippedUrlEnd.length;
							if (l1 == maxUrlLength) l1=0;
							var front = element.substringData(0, maxUrlLength-l1);
							front = front+clippedUrlEnd;
							var tn = document.createTextNode(front);
							element.parentNode.replaceChild(tn,element.parentNode.firstChild);
						}
					}

					function externalLinks(doc) {
						if (doc == null) doc = content.document;
						if (!doc.getElementsByTagName) return;
						var anchors = doc.getElementsByTagName("a");
						//alert("links len " + anchors.length);
						for (var i=0; i<anchors.length; i++) {
							var anchor = anchors[i];
							if (anchor.getAttribute("href") &&
							anchor.getAttribute("rel") == "external")
							anchor.target = "_blank";
						}
					}

					function commentSpellCheck(doc) {
						if (doc == null) doc = content.document;
						var commentdiv = doc.getElementById(SMACK_OUTWITCOMMENTDIV);
						if (commentdiv != null) {
							commentdiv.spellcheck = true;
						}
					}

					function registerSmackChatListeners(doc) {
						//reset flags
						swaksmack.productListenerAdded = false;

						var chatDiv = doc.getElementById('chat');

						if (chatDiv != null){
							chatDiv.addEventListener('DOMNodeInserted', smackChatPostInserted, false);
							chatDiv.addEventListener('DOMAttrModified', smackChatPostAttrModified, false);
							chatDiv.addEventListener('DOMNodeRemoved', smackChatPostRemoved, false);
						}

						var guru=doc.getElementById('guruContainer');
						if (guru != null){
							guru.addEventListener('DOMAttrModified',smackChatGuruAttrModified,false);
						}
						var chatHeader = doc.getElementById('chatHeader');
						if (chatHeader != null) {
							chatHeader.addEventListener('dblclick', function(event) {
								toggleChat();
							}, false);
						}


						var msgCenterDiv = doc.getElementById('leftPanel');

						if (msgCenterDiv != null){

							if (SS_getPreference(SMACK_ENHANCEHIDEAVATARS))		 {
								msgCenterDiv.addEventListener('DOMNodeRemoved', function(event) {
									//alert('DOMNodeRemoved ' + event.target.id);
									smackPoll();
									if (SS_getPreference(SMACK_ENHANCEHIDEAVATARS))		 {
										var state = swaksmack.SS_JF.getState();
										if (state== SMACK_STATE_OUTWITRESULT || state == SMACK_STATE_OUTWITVOTE || state == SMACK_STATE_OUTWIT_VOTED || state == SMACK_STATE_NONGURUDEALSOLD) {
											//alert('DNR hide images');
											hideAllAvatarImages();
										}
									}
								}, false);



							}

							//TODO--start of amazon query integration

							msgCenterDiv.addEventListener('DOMNodeRemoved', function(event) {
								var retprice = swaksmack.SmackShopDoc.getElementById('retailPrice');


								if (retprice == null) {
									swaksmack.productListenerAdded = false;
								}
								else if (swaksmack.productListenerAdded == false && retprice != null) {
									//alert('adding price event listener');
									//swaksmack.alertManager.swakAlert(SMACK_ALERT_GURUGUESS, true, 60000, true);
									swaksmack.productListenerAdded = true;
									retprice.addEventListener('dblclick', function(event) {

										//	alert('smackpotheader div dblclick');
										//swakSmackPotCalc();

										SwakSubmitProductQuery();
									},false);
								}
							}, true);



						}




						var e1=doc.getElementsByName('user_guess');
						var guruinput;
						for (var i=0;i<e1.length;i++) {
							if (e1[i].name == 'user_guess') {
								guruinput = e1[i];
								break;
							}
						}
						//alert('init guruinput');
						if (guruinput != null) {
							if (SS_ggListenerAdded == false) {
								SS_ggListenerAdded = true;
								guruinput.addEventListener('dblclick', function(event) {
									//alert('launchCalcWindow');
									launchCalcWindow();
								}, false);   //was true
							}
						}
						else {
							SS_ggListenerAdded = false;
						}


						///smackpot test stuff
						var spheaderDiv = doc.getElementById('smackPotHeader');

						if (spheaderDiv != null){
							
							var img = swaksmack.SmackShopDoc.createElement('img');
							img.setAttribute('src','chrome://swaksmack/skin/calculator.png');
							img.setAttribute('id','swaksmackSmackPotCalc');
							//img.src="chrome://swaksmack/skin/calculator.png";
							spheaderDiv.appendChild(img);
							
							img.addEventListener('mouseover', function(event) {
								event.target.setAttribute('src','chrome://swaksmack/skin/calculator_over.png');
							}, false);
							
							img.addEventListener('mouseout', function(event) {
								event.target.setAttribute('src','chrome://swaksmack/skin/calculator.png');
							}, false);
							
							img.addEventListener('click', function(event) {
								swakSmackPotCalc();
							}, false);
							
							/*
							spheaderDiv.addEventListener('dblclick', function(event) {
								//alert('smackpotheader div dblclick');
								swakSmackPotCalc();

							}, false);
							*/
						}

						/////////////////////////////


					}
					
	function addPlayPause(doc) {
		if (doc == null) return;
		var cc = doc.getElementById('comment_comment');
		//var cc = doc.getElementById('post_a_comment');
		if (cc == null) return;
		
		var pcc = cc.parentNode;
		var cf = getElementsByClassName("clearFloat",pcc);
		var pw = doc.getElementById('post_wait');
		var img = swaksmack.SmackShopDoc.createElement('img');
		img.setAttribute('src','chrome://swaksmack/skin/pause-chat.png');
		img.setAttribute('id','swaksmackChatPause');
		img.addEventListener('mouseover', function(event) {
			event.target.setAttribute('src','chrome://swaksmack/skin/pause-chat_over.png');
		}, false);
		
		img.addEventListener('mouseout', function(event) {
			event.target.setAttribute('src','chrome://swaksmack/skin/pause-chat.png');
		}, false);
		
		img.addEventListener('click', function(event) {
			//pause chat
			//alert('pause chat');
			var paused = toggleChat();
			/*
			if (paused) {
				var pauseImg = swaksmack.SmackShopDoc.getElementById('swaksmackChatPause');
				pauseImg.style.display='none';
				var playImg = swaksmack.SmackShopDoc.getElementById('swaksmackChatPlay');
				playImg.style.display='';
			}
			*/
		}, false);
		//img.style.margin='0px 0px 0px 5px';
		var jellyfishstrings = document.getElementById("swaksmack-strings");
		img.title = jellyfishstrings.getString("pause_tooltip");
		//pcc.insertBefore(img,cf[0]);
		pcc.insertBefore(img,pw);
		
		var img2 = swaksmack.SmackShopDoc.createElement('img');
		img2.setAttribute('src','chrome://swaksmack/skin/play-chat.png');
		img2.setAttribute('id','swaksmackChatPlay');
		
		img2.addEventListener('mouseover', function(event) {
			event.target.setAttribute('src','chrome://swaksmack/skin/play-chat_over.png');
		}, false);
		
		img2.addEventListener('mouseout', function(event) {
			event.target.setAttribute('src','chrome://swaksmack/skin/play-chat.png');
		}, false);
		
		img2.addEventListener('click', function(event) {
			//resume chat
			//alert('play chat');
			var paused = toggleChat();
			/*
			if (!paused) {
				var pauseImg = swaksmack.SmackShopDoc.getElementById('swaksmackChatPause');
				pauseImg.style.display='';
				var playImg = swaksmack.SmackShopDoc.getElementById('swaksmackChatPlay');
				playImg.style.display='none';
			}	
			*/		
		}, false);				
		//hide play for initialization
		img2.style.display='none';
		//img2.style.margin='0px 0px 0px 5px';
		img2.title = jellyfishstrings.getString("play_tooltip");
		//pcc.insertBefore(img2,cf[0]);
		pcc.insertBefore(img2,pw);
		
		

	}				

		            function swakSendPM(e) {
            		    
			            var ctx = swaksmack.postPopupNode;
			            var ci = getCommentInfo(ctx);
			            var chatNick = getElementsByClassName('chatNick',ci);
			            var ref = chatNick[0].getAttribute('href');
			            var paurl = 'http://www.jellyfish.com' + ref;
			            var username = chatNick[0].textContent;
            			
		                initPMRequest(username, paurl,  window.content.document, e);		
              
		            }

					function SwakSubmitProductQuery() {

						var product = swaksmack.SmackShopDoc.getElementById('productNameAnchor');
						if (product == null || product == 'undefined') return;
						var pt = product.textContent;

						var tu = new AmazonProductRequest(pt);  //was pt
						var amazonCB = {
							ondone : function(handle){
								//alert('APR done');
								var list = handle.amazonInfoList;
								if (list == null) return;
								var api = list.shift();
								alert('url: ' + api.prodURL + ' price: ' + api.prodPrice);
							},

							onerror : function(handle){
								//alert('APR error');
							}
						}
						tu.execute(amazonCB);
					}

					function smackChatPostAttrModified(event) {
						//alert('smackChatPostAttrModified entry');
						if (swaksmack.smackchatIdArray == null) {
							return;
						}
						
						//need to to proces the last added chat comment
						var processed = false;
						while (swaksmack.smackchatIdArray.length >0) {
							//alert('smackChatPostAttrModified length >0 ' + swaksmack.smackchatIdArray.length);
							//check content
							if (swaksmack.smackShopContentWindow == null || swaksmack.SS_JF.isUnknownState() == true || swaksmack.SmackShopDoc == null) {
								//alert('swaksmack state is unknown...fixing');
								if (isSmackShopArea(content.document) == true) {
									//alert('runtime reinitialization of smackShopContentWindow');
									swaksmack.smackShopContentWindow = gBrowser.contentWindow;
									swaksmack.SmackShopDoc = content.document;
								}
								else {
									var cw = SS_getSmackShoppingWindow();
									//alert('cw ' + cw);
									if (cw != null) {
										swaksmack.smackShopContentWindow = cw;
										swaksmack.SmackShopDoc = cw.document;
									}
								}
							}


							//alert('smackChatPostAttrModified');
							execute(swaksmack.smackchatIdArray.pop(), true, swaksmack.SmackShopDoc);
							//var chatPost = getElementsByClassName("chatPost",swaksmack.SmackShopDoc);
							//externalLinks(swaksmack.SmackShopDoc);
							//externalLinks(event.target);
							if (processed == true) continue;
							//setTimeout("smackPoll()",SS_alertTimeOut);
							if (SS_getPreference(SMACK_ALTALERTMONITOR) == false) {
								//alert('none alt alert poll');
								swakCheckStateAlerts();
							}
							if (swaksmack.SS_SBM.isMonitoring() == false) {
								swaksmack.SS_SBM.monitorState(SS_getPreference(SMACK_SBSALEINTERVAL));
							}
							updatePMLR();
							setChatSpeed();
							//SS_oldState = swaksmack.SS_JF.getState();//swaksmack.alertManager.state;
							//swaksmack.alertManager.updateAlertState(swaksmack.SmackShopDoc);


							if (SS_ChatHeaderText != null ) {
								//reset chatHeader content
								if (SS_chatHeaderChange == true && swaksmack.SS_JF.isChatPaused() == false) {
									updateChatHeader(true);
								}

							}
							processed = true;
						}



					}

					function swakCheckStateAlerts() {
						if (SS_getPreference(SMACK_ENABKEALERTMONITORDELAY) == true) {
							setTimeout("smackPoll()",SS_alertTimeOut);
						}
						else {
							smackPoll();
						}
					}

					function smackChatPostInserted(event) {
						if (swaksmack.smackchatIdArray == null || swaksmack.SmackShopDoc == null) {
							return;
						}

						var cn = event.target.className;
						var id = event.target.id;
						if (id == null || id == 'undefined') {
							return;
						}

						if (cn != null && (cn == 'commentFloatContainer' || cn == 'swaksmackUnhighlightUser' || cn =='swaksmackHighlightUser' || cn == 'swaksmackReply' || cn =='swaksmackAction')) {
							return;
						}

						while (swaksmack.smackchatIdArray.length >0) {execute(swaksmack.smackchatIdArray.pop(), true, swaksmack.SmackShopDoc);}


						swaksmack.smackchatIdArray.push(event.target);
						/*
						if (SS_getPreference(SMACK_ALTALERTMONITOR) == true) {
							swakCheckStateAlerts();
						}
						*/

					}

					//shared by both smack chat and LR
					function smackChatPostRemoved(event) {
						var cid = event.target.id;
						if (cid != null) {
							var cin = cid.indexOf('comment');
							if (cin != -1) {
								//alert(cin + ' comment removed ' + cid);
								var hl = getElementsByClassName('swaksmackHighlightUser',event.target);
								if (hl != null && hl[0] != null) {
									hl[0].removeEventListener('click', enhancedReply,false);
									hl[0].removeEventListener('click', enhancedHighlight,false);
									hl[0].removeEventListener('click', enhancedAction,false);
									//alert(cin + ' comment hl/reply events removed ' + hl[0].className);
								}
								var uhl = getElementsByClassName('swaksmackUnhighlightUser',event.target);
								if (uhl != null && uhl[0] != null) {
									uhl[0].removeEventListener('click', enhancedReply,false);
									uhl[0].removeEventListener('click', enhancedHighlight,false);
									uhl[0].removeEventListener('click', enhancedAction,false);
									//alert(cin + ' comment uhl/reply events removed ' + uhl[0].className);
								}
							}
							else {
								//alert(cin + ' element removed ' + cid);
							}
						}
					}

			function smackChatGuruAttrModified(event) {
				
				
							var gh = swaksmack.SmackShopDoc.getElementById('guruHeader');
							//alert('smackChatGuruAttrModified gh' +gh);
							if (gh != null) {
								var ssgc = swaksmack.SmackShopDoc.getElementById('swaksmackGuruCalc');
								if (ssgc == null) {
									//alert('adding calc button');
									var img = swaksmack.SmackShopDoc.createElement('img');
									img.setAttribute('src','chrome://swaksmack/skin/calculator.png');
									img.setAttribute('id','swaksmackGuruCalc');
									//img.src="chrome://swaksmack/skin/calculator.png";
									gh.appendChild(img);
									
									img.addEventListener('mouseover', function(event) {
										event.target.setAttribute('src','chrome://swaksmack/skin/calculator_over.png');
									}, false);
									
									img.addEventListener('mouseout', function(event) {
										event.target.setAttribute('src','chrome://swaksmack/skin/calculator.png');
									}, false);
									
									img.addEventListener('click', function(event) {
										launchCalcWindow();
									}, false);
								}
								checkGuruGuess(false);
							}
				
				
				if (swaksmack.alertManager == null) {
					return;
				}
				swaksmack.alertManager.updateAlertState();
			}

			function registerLivingRoomChatListeners(doc) {
				var chatDiv = doc.getElementById('chat');

				if (chatDiv != null){
					chatDiv.addEventListener('DOMNodeInserted', livingRoomChatPostInserted, false);
					chatDiv.addEventListener('DOMAttrModified', livingRoomChatPostAttrModified, false);
					chatDiv.addEventListener('DOMNodeRemoved', smackChatPostRemoved, false);
				}

			}

			function livingRoomChatPostInserted(event) {
				if (swaksmack.smackLRIdArray == null || swaksmack.LivingRoomDoc == null) {
					return;
				}

				var cn = event.target.className;
				var id = event.target.id;
				if (id == null || id == 'undefined') {
					return;
				}

				if (cn != null && (cn == 'commentFloatContainer' || cn == 'swaksmackUnhighlightUser' || cn =='swaksmackHighlightUser' || cn == 'swaksmackReply')) {
					return;
				}

				while (swaksmack.smackLRIdArray.length >0) {execute(swaksmack.smackLRIdArray.pop(), true, swaksmack.LivingRoomDoc);}


				swaksmack.smackLRIdArray.push(event.target);

			}

			function livingRoomChatPostAttrModified(event) {
				if (swaksmack.smackLRIdArray == null || swaksmack.LivingRoomDoc == null) {
					return;
				}
				//need to to proces the last added chat comment
				while (swaksmack.smackLRIdArray.length >0) {
					execute(swaksmack.smackLRIdArray.pop(), true, swaksmack.LivingRoomDoc);
					externalLinks(swaksmack.LivingRoomDoc);
					setChatSpeed();
					updatePMLR();
				}
			}

			function checkGuruGuess(alertsEnabled) {
				if (alertsEnabled == null) alertsEnabled = true;
				//if (doc == null) doc = content.document;
				///////////////////

				var e1=swaksmack.SmackShopDoc.getElementsByName('user_guess');
				if (e1 != null) {
					var guruinput;
					for (var i=0;i<e1.length;i++) {
						if (e1[i].name == 'user_guess') {
							guruinput = e1[i];
							//alert('AVL gg user guess found');
							break;
						}
					}
					if (guruinput != null) {
						try {
							//var guruError = swaksmack.SmackShopDoc.getElementById('guruError');
						//	var gestyle = guruError.style.display;
								var ssgc = swaksmack.SmackShopDoc.getElementById('swaksmackGuruCalc');
								if (ssgc != null) {
								  if (guruinput.style.display != 'none') {
										ssgc.style.display='';
									}
									else {
										ssgc.style.display='none';
									}
								}
							
						}
						catch(x){}
						if (SS_ggListenerAdded == false) {
							//	alert('GG add event list' + SS_ggListenerAdded);
							SS_ggListenerAdded = true;
							
							//var gh = swaksmack.SmackShopDoc.getElementById('guruHeader');
							/*
							var ssgc = swaksmack.SmackShopDoc.getElementById('swaksmackGuruCalc');
							if (ssgc != null) {
								ssgc.style.display='';
							}
							*/
							
				/*			
							var gh = swaksmack.SmackShopDoc.getElementById('guruHeader');
							//alert('gh' +gh);
							var img = swaksmack.SmackShopDoc.createElement('img');
							img.setAttribute('src','chrome://swaksmack/skin/calculator.png');
							//img.src="chrome://swaksmack/skin/calculator.png";
							gh.appendChild(img);
							
							img.addEventListener('mouseover', function(event) {
								event.target.setAttribute('src','chrome://swaksmack/skin/calculator_over.png');
							}, false);
							
							img.addEventListener('mouseout', function(event) {
								event.target.setAttribute('src','chrome://swaksmack/skin/calculator.png');
							}, false);
							
							img.addEventListener('click', function(event) {
								launchCalcWindow();
							}, false);
							*/
							guruinput.addEventListener('dblclick', function(event) {
								launchCalcWindow();
							}, false);

							var gcon = swaksmack.SmackShopDoc.getElementById('guruContainer');
							if (gcon != null) {
								gcon.addEventListener('submit', function(event) {
									try {
										var ssgch = swaksmack.SmackShopDoc.getElementById('swaksmackGuruCalc');
										if (ssgch != null && gestyle == 'none') {
											ssgch.style.display='none';
										}
											//alert('guruguess ans submitted');
											swakstats.incrementGuruGuessPlayed();
											this.removeEventListener('submit',arguments.callee,false);
									}
									catch (x) {
										//alert(x);
										}
								}, false);
							}
						}
						} else {
							SS_ggListenerAdded = false;
								var ssgch = swaksmack.SmackShopDoc.getElementById('swaksmackGuruCalc');
								if (ssgch != null) {
									ssgch.style.display='none';
								}
							//alert('guruinput NOT found, unable to perform calculations.SS_ggListenerAdded = false; ' + );
						}

					} //end e1
					else {
						//alert('SS_ggListenerAdded set to false');
						SS_ggListenerAdded = false;
						var ssgch = swaksmack.SmackShopDoc.getElementById('swaksmackGuruCalc');
						if (ssgch != null) {
							ssgch.style.display='none';
						}
					}

					////////////////////


					if (alertsEnabled && swakalerts.guruguessAlertAck == false && swaksmack.SmackShopDoc.getElementById(SMACK_OUTWITGURUGUESSDIV) != null) {
						//	alert(SS_guruguessAlertAck + ' (SS_guruguessAlertAck) checkGuruGuess found GG (div) ' + SS_doc.getElementById(SMACK_OUTWITGURUGUESSDIV));
						var guruguessAlertPref = SS_getPreference(SMACK_GURUGUESSALERT);
						//alert('guruguessAlertPref ' + guruguessAlertPref);
						//SS_guruguessAlertAck = true;
						swakalerts.guruguessAlertAck = true;

						if (guruguessAlertPref == "audio" || guruguessAlertPref == "both"){
							//alert('play audio');
							var soundFile = SS_getPreference(SMACK_AUDIOSOUND_OUTWIT);
							if (soundFile == null || soundFile == '') {
								soundFile = AUDIO_DIR + DEFAULT_SOUND;
							}
							swaksmack.audioManager.playAudioAlert(soundFile);
						}
						if (guruguessAlertPref == "alert" || guruguessAlertPref == "both"){
							//alert('show GG alert entered');
							//var jellyfishstrings = document.getElementById("swaksmack-strings");
							//var alert3 = jellyfishstrings.getString("guruguessWarn1");
							//alert(alert3 +'\n'+Date());
							var leftPanel = swaksmack.SmackShopDoc.getElementById('leftPanel');
							if (leftPanel != null) {
								leftPanel.addEventListener('click',  function(event) {
									swaksmack.alertManager.alertWindow.close();
									//remove this event listener
									this.removeEventListener('click',arguments.callee,false);
								}, false);
							}
							swaksmack.alertManager.swakAlert(SMACK_ALERT_GURUGUESS, true, 60000, true);
						} 
						else if (swaksmack.SmackShopDoc.getElementById(SMACK_OUTWITGURUGUESSDIV) == null) {
							swakalerts.guruguessAlertAck = false;
						}
					}
					else {
						//this constantly entered during a SD show after guess is in
						//alert(SS_guruguessAlertAck + ' (SS_guruguessAlertAck) checkGuruGuess failed to find GG (div) ' + SS_doc.getElementById(SMACK_OUTWITGURUGUESSDIV));
					}
				}

					var SS_oldState = null;
					var SS_outwitOptInCounted = false;
					var SS_outwitVoteCounted = false;
					var SS_outwitSelected = false;
					var SS_smackpotEntryCounted = false;
					var SS_guruguessmade = false;
					var SS_smackpotCoinsWon = false;
					var SS_ouwitPointWon = false;
					var SS_outwitOptinSubmitted = false;

					function smackPoll() {
						//SS_oldState = swaksmack.SS_JF.getState();
						//hideAllAvatarImages();
						var cState = swaksmack.SS_JF.getState();
						//if (cState != SS_oldState) {
						swaksmack.SS_SBM.refreshState();
						//alert('cstate: ' + cState);
						//}
						if (cState == SMACK_STATE_OUTWITRESULT || cState == SMACK_STATE_NONGURUDEAL
						|| cState == SMACK_STATE_GURUGUESSSOLD || cState == SMACK_STATE_SMACKPOT_BETCLOSED
						|| cState == SMACK_STATE_PREVIEW || cState == SMACK_STATE_OUTWITMISSED) {

							swakalerts.outwitAlertAck = false;
							swakalerts.outwitVoteAck = false;
							swakalerts.smakpotAlertAck = false;
							swakalerts.guruguessAlertAck = false;

							SS_ggListenerAdded = false;

							//reset
							SS_outwitOptInCounted = false;
							SS_outwitVoteCounted = false;
							SS_outwitSelected = false;
							SS_guruguessmade = false;
							SS_smackpotCoinsWon = false;
							SS_smackpotEntryCounted = false;
							SS_outwitOptinSubmitted = false;

							if (cState == SMACK_STATE_PREVIEW) {
								swaksmack.coinsWonDuringShow = 0;
							}


							//still want to process result below
							if (cState != SMACK_STATE_OUTWITRESULT && cState != SMACK_STATE_GURUGUESSSOLD) {
								SS_ouwitPointWon = false;
								return;
							}
						}
						//another safety check since we don't have a real state machine to eval transistions
						if (SS_oldState == SMACK_STATE_NONGURUDEAL && cState == SMACK_STATE_OUTWITOPTIN) {

							swakalerts.outwitAlertAck = false;
							swakalerts.outwitVoteAck = false;
							swakalerts.smakpotAlertAck = false;
							swakalerts.guruguessAlertAck = false;

							SS_outwitOptInCounted = false;
							SS_outwitVoteCounted = false;
							SS_outwitSelected = false;
							SS_smackpotEntryCounted = false;
							SS_guruguessmade = false;
							SS_smackpotCoinsWon = false;
							SS_ouwitPointWon = false;
							SS_outwitOptinSubmitted = false;
						}
						/*
						if (cState == SS_oldState) {
						return;

						}
						else {
						alert(SS_oldState + ' (old) diff state (new) ' + cState);
						}
						*/
						var outwitAlertPref = "none";
						var outwitVoteAlertPref = "none";
						var guruguessAlertPref = "none";
						var smackpollAlertPref = "none";
						var alertsEnabled = true;
						try {
							outwitAlertPref = SS_getPreference(SMACK_OUTWITALERT);
							outwitVoteAlertPref = SS_getPreference(SMACK_OUTWITVOTEALERT);
							guruguessAlertPref = SS_getPreference(SMACK_GURUGUESSALERT);
							smackpollAlertPref = SS_getPreference(SMACK_SMACKPOTALERT);
							alertsEnabled = SS_getPreference(SMACK_ALERTGLOABLEENABLE);
						}
						catch(Exception){
							//alert('Error with alert options.  Notify the swaksmack development team.');
						}



						//alert('smackpoll cstate: ' + cState);

						if (cState == SMACK_STATE_OUTWITOPTIN){
							if (alertsEnabled && outwitAlertPref != "none" && swakalerts.outwitAlertAck == false) {
								swakalerts.outwitAlertAck = true;
								SS_outwitSelected = false;
								if (outwitAlertPref == "both" || outwitAlertPref == "audio"){
									var soundFile = SS_getPreference(SMACK_AUDIOSOUND_OUTWIT);
									if (soundFile == null || soundFile == '') {
										soundFile = AUDIO_DIR + DEFAULT_SOUND;
									}
									swaksmack.audioManager.playAudioAlert(soundFile);
								}
								if (outwitAlertPref == "both" || outwitAlertPref == "alert"){
									var capans = swaksmack.SmackShopDoc.getElementById('captcha_answer');
									if (capans != null) {
										capans.addEventListener('click',  function(event) {
											swaksmack.alertManager.alertWindow.close();
											//remove this event listener
											this.removeEventListener('click',arguments.callee,false);
										}, false);
									}

									swaksmack.alertManager.swakAlert(SMACK_ALERT_OUTWITOPTIN, true, 60000, true);
								}
							}

							var owc = swaksmack.SmackShopDoc.getElementById('outwitContainer');
							if (owc != null) {
								owc.addEventListener('submit',  function(event) {
									//alert('outwit opt in submitted');
									SS_outwitOptinSubmitted = true;
									//swaksmack.alertManager.alertWindow.close();
									//remove this event listener
									this.removeEventListener('submit',arguments.callee,false);
								}, true);
							}

						}
						else if (cState == SMACK_STATE_OUTWITVOTE){
							if (alertsEnabled && outwitVoteAlertPref != "none" && swakalerts.outwitVoteAck == false) {
								swakalerts.outwitVoteAck = true;
								swakalerts.outwitAlertAck = false;
								swakalerts.smakpotAlertAck = false;
								swakalerts.guruguessAlertAck = false;
								//check if already checked
								var owc = swaksmack.SmackShopDoc.getElementById('outwitContainer');
								if (owc == null) return;
								var anschecked = getElementsByClassName('outwitAnswerChecked', owc);
								if (anschecked != null && anschecked[0] != null) {
									//alert('answer already checked');
									return;
								}
								SS_outwitSelected = false;
								if (outwitVoteAlertPref == "both" || outwitVoteAlertPref == "audio") {
									var soundFile = SS_getPreference(SMACK_AUDIOSOUND_OUTWIT);
									if (soundFile == null || soundFile == '') {
										soundFile = AUDIO_DIR + DEFAULT_SOUND;
									}
									swaksmack.audioManager.playAudioAlert(soundFile);
								}
								if (outwitVoteAlertPref == "both" || outwitVoteAlertPref == "alert") {
									var leftPanel = swaksmack.SmackShopDoc.getElementById('leftPanel');
									if (leftPanel != null) {
										leftPanel.addEventListener('click',  function(event) {
											swaksmack.alertManager.alertWindow.close();
											//remove this event listener
											this.removeEventListener('click',arguments.callee,false);
										}, false);
									}
									swaksmack.alertManager.swakAlert(SMACK_ALERT_OUTWITVOTE, true, 60000, true);
								}
								//alert ack			}
							}
						}
						else if (cState == SMACK_STATE_SMACKPOT_BETOPEN){
							if (alertsEnabled && smackpollAlertPref != "none" && swakalerts.smakpotAlertAck == false) {

								swakalerts.smakpotAlertAck = true;
								if (smackpollAlertPref == "both" || smackpollAlertPref == "audio") {
									var soundFile = SS_getPreference(SMACK_AUDIOSOUND_OUTWIT);
									if (soundFile == null || soundFile == '') {
										soundFile = AUDIO_DIR + DEFAULT_SOUND;
									}
									swaksmack.audioManager.playAudioAlert(soundFile);
								}
								if (smackpollAlertPref == "both" || smackpollAlertPref == "alert"){
									//alert('smack pot alert');
									var leftPanel = swaksmack.SmackShopDoc.getElementById('leftPanel');
									if (leftPanel != null) {
										leftPanel.addEventListener('click',  function(event) {
											swaksmack.alertManager.alertWindow.close();
											//remove this event listener
											this.removeEventListener('click',arguments.callee,false);
										}, false);
									}
									swaksmack.alertManager.swakAlert(SMACK_ALERT_SMACKPOTGUESS, true, 60000, true);
								}
							}
						}
						else if (cState == SMACK_STATE_GURUGUESSENTER){
							//alert('REMOVE check guru state smack poll state ' + cState);
							checkGuruGuess(alertsEnabled);
						}
						else if (SS_outwitOptinSubmitted == true && SS_outwitOptInCounted == false && cState == SMACK_STATE_OUTWITOPTINENTERED){
							SS_outwitOptInCounted = true;
							SS_outwitOptinSubmitted = false;
							swakstats.incrementOutwitOptIn();
						}
						else if (SS_outwitVoteCounted == false && cState == SMACK_STATE_OUTWIT_VOTED){
							SS_outwitVoteCounted = true;
							swakstats.incrementOutwitVote();
						}
						else if (SS_smackpotEntryCounted == false && cState == SMACK_STATE_SMACKPOT_BETMADE){
							//alert('increment sp bet made');
							SS_smackpotEntryCounted = true;
							swakstats.incrementSmackPotPlayed();
							try {
								var bet = swaksmack.SmackShopDoc.getElementById('myBet');
								if (bet != null) {
									var c = bet.textContent;
									var coins = parseInt(c);
									swakstats.incrementSmackPotBet(coins);
								}
							}
							catch(x){}
						}
						else if (SS_outwitSelected == false && cState == SMACK_STATE_OUTWITCONTESTANTSELECTED){
							SS_outwitSelected = true;
							try {
								var pnid = swaksmack.SmackShopDoc.getElementById('playerName');
								if (pnid != null) {
									var nickname = swaksmack.SS_JF.getNickName();
									if (nickname == pnid.textContent) {
										swakstats.incrementOutwitSelected();
									}
								}
							}
							catch(x){}


						}
						else if(SS_smackpotCoinsWon == false && cState == SMACK_STATE_SMACKPOT_RESULTS) {
							SS_smackpotCoinsWon = true;
							try {
								var coins = swaksmack.SS_JF.getSmackPotCoinsWon();
								swakstats.incrementSmackPotCoinsWon(coins);
								swaksmack.coinsWonDuringShow +=coins;
								swaksmack.coinsWonOnLastItem = coins;
								swaksmack.coinsWonDuringSession +=coins;
								//alert('coins won ' + coins);
							}
							catch (x) {}
							insertSoldPrice();
							
						}
						else if (SS_ouwitPointWon == false && cState == SMACK_STATE_OUTWITRESULT) {
							SS_ouwitPointWon = true;
							swaksmack.SS_JF.incrementOutwitPoint();
						}
						else if (cState == SMACK_STATE_GURUGUESSWHEELSPIN) {
							if (alertsEnabled && swakalerts.wheelSpinAlertAck == false) {
								swakalerts.wheelSpinAlertAck = true;
								
									var nickname = swaksmack.SS_JF.getNickName();
									var c = swaksmack.SS_JF.getWheelContestant();
									if (c == nickname) {
										if (guruguessAlertPref == "audio" || guruguessAlertPref == "both"){
											var soundFile = SS_getPreference(SMACK_AUDIOSOUND_OUTWIT);
											if (soundFile == null || soundFile == '') {
												soundFile = AUDIO_DIR + DEFAULT_SOUND;
											}
											swaksmack.audioManager.playAudioAlert(soundFile);
										}
										if (guruguessAlertPref == "alert" || guruguessAlertPref == "both"){
											swaksmack.alertManager.swakAlert(SMACK_ALERT_GURUWHEELSPIN, true, 60000, true);
										}
									}
								
							}
						}
						else if (cState == SMACK_STATE_GURUGUESSSOLD) {
							//alert('sp --SMACK_STATE_GURUGUESSSOLD');
							insertSoldPrice();
						}
					}
					
					function insertSoldPrice() {
						
						try {
							var bd = swaksmack.SmackShopDoc.getElementById('bestDeal');
							if (bd == null) return;
							var swakSold = getElementsByClassName('swakBestDealSoldPrice',bd);
							if (swakSold !== null && swakSold[0] != null) return;
							var retailPrice = swaksmack.SS_JF.getRetailPrice();
			  			var discountPercent = swaksmack.SS_JF.getDiscount();
			  			var salePrice = swaksmack.SS_JF.getSalePrice(retailPrice,discountPercent);
			  			if (salePrice == null) {
			  				return;
			  			}
			  			var chtml = bd.innerHTML;
							chtml = chtml + "<span class=\"swakBestDealSoldPrice\">Sold: $" + salePrice +"</span>";
							//chtml = chtml + " Sold for: <span class=\"swakBestDealSoldPrice\">$" + salePrice +"</span>";
							bd.innerHTML = chtml;
		  			}
		  			catch (x) {
		  				//alert('insertSoldPrice error ' + x);
		  			}
					}

					function hideAllAvatarImages() {

						var ha = "/img/shoppers/avatars/.*";
						var regExp = new RegExp(ha,"ig");
						//alert(SS_doc + ' hideAllAvatarImages ' + regExp);
						var img = null;
						for(i=swaksmack.SmackShopDoc.images.length-1;i>=0;i--){
							img = swaksmack.SmackShopDoc.images[i];
							var isrc = swaksmack.SmackShopDoc.images[i].src;
							if (isrc != null && img.style.display != 'none') {
								var hide = regExp.test(isrc);
								if (hide) {
									//alert('hide ' + img.id);
									//SS_doc.images[i].src='';
									img.style.display='none';
								}
							}

						}
						swaksmack.SmackShopDoc.close();

					}

					// swaksmack context menu stuff

					function swakContextVisibilityOn() {
						var menuitems = ['swaksmack-context-menu',
						'contextmenu-addkeywords',
						'contextmenu-listkeywords',
						'contextmenu-clearkeywords',
						'contextmenu-chatdisplayhl'];
						for (var i=menuitems.length-1;i>=0;i--){
							document.getElementById(menuitems[i]).setAttribute('hidden','false');
						}
					}

					function swakContextShowing() {
						//alert('contextShowing');
						var menuitem = document.getElementById("contextmenu-addkeywords");
						if (gContextMenu.isTextSelected) {
							var keyword;
							if (gContextMenu.searchSelected)
							keyword = gContextMenu.searchSelected();
							else
								keyword = getBrowserSelection();
								if (keyword.length > SS_keywordDisplayLength)
								keyword = keyword.substr(0,SS_keywordDisplayLength-1) + "...";
								var displaytext = "Add \"" + keyword + "\" to SwakSmack highlights.";
								menuitem.setAttribute("label", displaytext);
								menuitem.setAttribute("hidden","false");
							}
							else {
								menuitem.setAttribute("hidden","true");
							}
						}

						function chatAddKeywords() {
							//alert('Do keyword stuff');
							var keyword = "";
							if (gContextMenu.onTextInput)
							{
								//alert('Do keyword stuff on textinput');
								keyword = document.popupNode;
								keyword = keyword.value.substring(keyword.selectionStart, keyword.selectionEnd);
								if (keyword.length>SS_keywordDisplayLength)
								keyword = keyword.substr(0,SS_keywordDisplayLength-1);
							}
							else
								{
									if (gContextMenu.searchSelected)
									keyword = gContextMenu.searchSelected();
									else
										keyword = getBrowserSelection();
										if (keyword.length == 0)
										{
											//do nothing? /?an alert?
											return;
										}
									}
									if (keyword.length>0)
									{
										//alert(keyword);
										SS_dynamicKeywords.push(keyword);
										JF_keywordlistRegExp = null;
										JF_usernamelistRegExp = null;
										JF_usernameArray = [];
										JF_keywordArray = [];
										highlightExistingComments(content.document);
									}

								}

								function toggleDisplayHighlighted() {
									if (isSmackShopArea(content.document)) {
										swaksmack.smackCommentsHidden = !swaksmack.smackCommentsHidden;
										toggleHighlightedCommentDisplay(content.document,swaksmack.smackCommentsHidden);
										updateDisplayHighlightedUI(content.document);
									}
									//for now no show highlight only in LR
									/*
									else if (isLRArea(content.document)) {
									swaksmack.lrCommentsHidden = !swaksmack.lrCommentsHidden;
									toggleHighlightedCommentDisplay(content.document,swaksmack.lrCommentsHidden);
									updateDisplayHighlightedUI(content.document);

									}
									*/


								}

								function updateDisplayHighlightedUI(doc) {
									if (doc == null) return;
									if (isSmackShopArea(doc) && gBrowser.contentWindow == swaksmack.smackShopContentWindow) {
										var sbitem = document.getElementById('ss-sb-pu-chatdisplayhl');
										if (sbitem != null) {
											sbitem.setAttribute('checked',swaksmack.smackCommentsHidden);
										}
										var cmitem = document.getElementById('contextmenu-chatdisplayhl');
										if (cmitem != null) {
											cmitem.setAttribute('checked',swaksmack.smackCommentsHidden);
										}
										SS_chatHeaderChange = true;
										updateChatHeader(!swaksmack.SS_JF.isChatPaused());
										//		alert('smack set check hidden ' + hidden);
									}
									//for now no show highlight only in LR
									/*
									else if (isLRArea(doc) && gBrowser.contentWindow != swaksmack.smackShopContentWindow) {
									var sbitem = document.getElementById('ss-sb-pu-chatdisplayhl');
									if (sbitem != null) {
									sbitem.setAttribute('checked',swaksmack.lrCommentsHidden);
									}
									var cmitem = document.getElementById('contextmenu-chatdisplayhl');
									if (cmitem != null) {
									cmitem.setAttribute('checked',swaksmack.lrCommentsHidden);
									}
									//	alert('lr set check hidden ' + hidden);
									}
									*/


								}

								function SwakProductSearchAmazon() {
									queryExternal(SEARCH_AMAZON_URL);
								}

								function SwakProductSearchEbay() {
									queryExternal(SEARCH_EBAY_URL);
								}
								
								function SwakProductSearchFroogle() {
									queryExternal(SEARCH_FROOGLE_URL);
								}
								
								function SwakProductSearchSmackOfShame() {
									//queryExternal(SEARCH_SMACKOSHAME_URL);
									querySmackOfShameExternal();
								}

								function chatClearKeywords(){
									//clear the dynamic keywords ad usernames
									//keywords specified in options are kept
									SS_dynamicKeywords = [];
									SS_dynamicUsernames = [];
									clearHighlightArrays();

								}

								function chatListKeywords(){
									//list keywords
									var words = SS_getPreference(SMACK_KEYWORDHL1);
									words += ', ';
									words += SS_getPreference(SMACK_KEYWORDHL2);
									words += ', ';
									words += SS_getPreference(SMACK_KEYWORDHL3);
	
									//alert('keyword ' + words);
									//alert('chatListKeywords SS_dynamicUsernames ' + SS_dynamicUsernames);
									var usernames = SS_getPreference(SMACK_USERNAMEHL1);	
									usernames += ', ';
									usernames += SS_getPreference(SMACK_USERNAMEHL2);
									usernames += ', ';
									usernames += SS_getPreference(SMACK_USERNAMEHL3);		
									
									//var usernames = SS_combinedUsernames.join(', ');
									var list = 'SwakSmack Keywords\n';
									if (words != '' && usernames != '') {
										list = list + '\nMain Keywords: \n';
										if (usernames != null) list = list + 'Usernames: ' + usernames +'\n';
										if (words != null) list = list + 'Keywords: ' + words +'\n';
									}
									if (SS_dynamicUsernames != null && SS_dynamicUsernames.length>0) {
										list = list + '\nDynamic Usernames: \n' +  SS_dynamicUsernames.toString();
									}
									if (SS_dynamicKeywords !=null && SS_dynamicKeywords.length>0) {
										list = list + '\nDynamic Keywords: \n' +  SS_dynamicKeywords.toString();
									}

									alert(list);
								}

								function toggleChat() {
									//alert('togglechat');
									if( isSmackShopArea(content.document) == false) {
										return;
									}
									var paused = swaksmack.SS_JF.toggleChat();
									//alert('paused ' + paused);
									//	var menuitem = document.getElementById("contextmenu-togglechat");
									var chatHeader = swaksmack.SmackShopDoc.getElementById('chatHeader');
									if (SS_ChatHeaderText == null || SS_ChatHeaderText == '') {
										SS_ChatHeaderText = chatHeader.innerHTML;
									}
									SS_chatHeaderChange = true;
									updateChatHeader();
									
									if (paused) {
										var pauseImg = swaksmack.SmackShopDoc.getElementById('swaksmackChatPause');
										pauseImg.style.display='none';
										var playImg = swaksmack.SmackShopDoc.getElementById('swaksmackChatPlay');
										playImg.style.display='';
									}
									else {	
										var pauseImg = swaksmack.SmackShopDoc.getElementById('swaksmackChatPause');
										pauseImg.style.display='';
										var playImg = swaksmack.SmackShopDoc.getElementById('swaksmackChatPlay');
										playImg.style.display='none';
									}
									
									//flag it again so thatthe status updates on the next post
									//this will return the header to normal
									SS_chatHeaderChange = true;
									return paused;
								}

								function updateChatHeader(resume) {
									if (swaksmack.SmackShopDoc == null || swaksmack.SS_JF == null) return;
									var chatHeader = swaksmack.SmackShopDoc.getElementById('chatHeader');
									if (chatHeader == null) return;
									if (SS_ChatHeaderText == null || SS_ChatHeaderText == '') {
										SS_ChatHeaderText = chatHeader.innerHTML;
									}
									if (resume == null) resume = false;
									var menuitem = document.getElementById("contextmenu-togglechat");
									var paused = swaksmack.SS_JF.isChatPaused();
									if (paused) {
										chatHeader.style.color = '#FF7800';
										menuitem.setAttribute("label",SS_getStringTableText("chat_resume"));
										var chatMsg = SS_getStringTableText("chat_paused1");
										chatHeader.innerHTML = SS_ChatHeaderText + "<b> : " + chatMsg+ "</b>";
									}
									else if (resume == false) {
										chatHeader.style.color = '#FF7800';
										menuitem.setAttribute("label",SS_getStringTableText("chat_pause"));
										var chatMsg = SS_getStringTableText("chat_resume1");
										var rn = SS_getRandomNumber(5);

										chatMsg = (rn <= 5)?SS_getStringTableText("chat_resume"+rn) : "chat_resume1";

										chatHeader.innerHTML = SS_ChatHeaderText + "<b> : " + chatMsg+ "</b>";

									}
									else {
										chatHeader.innerHTML = SS_ChatHeaderText;
									}


									if (swaksmack.smackCommentsHidden == true) {
										chatHeader.style.color = '#FF7800';
										var chatHidden = SS_getStringTableText('chat_header_display_hl_only');
										chatHeader.innerHTML = chatHeader.innerHTML + ' -- ' + chatHidden;
									}
									SS_chatHeaderChange = false;
								}

								function chatReply(event, pn) {

									//selection
									var replyText = '';

									if (gContextMenu.searchSelected)
									replyText = gContextMenu.searchSelected();
									else
										replyText = getBrowserSelection();
										if (replyText.length>0) {
											replyText = "\""+replyText+"\"";
										}


										//selection


										var ci = getCommentInfo(pn);
										//alert(pn.className + ' (org) --commentInfo element ' + ci.className);
										var chatNick = getElementsByClassName('chatNick',ci);


										var chatPrefix ='';
										if (chatNick != null && chatNick[0] != null) {
											var cpost = content.document.getElementById('comment_comment');
											cpost.value = buildReply(chatNick[0].textContent,replyText);
											cpost.focus();
											swakClearCurrentSelection();
										}
									}

									function getCommentInfo(commentNode) {
										try {
											if (commentNode == null) return null;
											if (commentNode.className == 'commentInfo') return commentNode;
											else if (commentNode.className == 'commentText') return commentNode.parentNode;
												else if (commentNode.className == 'chatNick') return commentNode.parentNode;
													else if (commentNode.className == 'chatGuru') return commentNode.parentNode;
														else if (commentNode.className == 'chatTime') return commentNode.parentNode;
															else if (commentNode.className == 'swaksmackHighlightUser') return commentNode.parentNode;
																else if (commentNode.className == 'swaksmackUnhighlightUser') return commentNode.parentNode;
																	else if (commentNode.className == 'swaksmackReply') return commentNode.parentNode;
																		else if (commentNode.className == 'chatAvatar') {
																			//not as straightforward, but navigation is simple
																			//find chatPost and then commentInfo
																			//alert('chatAvatar class found, parent parent parent className ' + commentNode.parentNode.parentNode.parentNode.className);
																			var cChatPost = commentNode.parentNode.parentNode.parentNode;
																			//minor recursion to find info from chatPost
																			return getCommentInfo(cChatPost);
																		}
																		else if (commentNode.className == 'chatPost') {
																			//the 3rd child of the chat post is the commentinfo
																			var ci = commentNode.childNodes[2];
																			if (ci != null && ci.className == 'commentInfo') {
																				return ci;
																			}
																			return null;
																		}
																		else {
																			//alert('unhandled commentNode.className ' + commentNode.className);
																			return null;
																		}
																		return null;
																	}
																	catch (Exception){
																		return null;
																	}
																}
																
		function swakActionIgnore() {
			var ctx = swaksmack.postPopupNode;
			var ci = getCommentInfo(ctx);
			var chatNick = getElementsByClassName('chatNick',ci);
			var username = chatNick[0].textContent;
			var msg = "Ignore that no good, lily-livered, blight on society miscreant " + username + "?";
			var ans = confirm(msg);
			if (ans) {
				var result = swakAppendWordToCharPref(username,SMACK_IGNORELIST1);
				if (result) {
					clearHighlightArrays();
				}
			}
		}
		
		function swakActionInitHighlight(event) {
			var username = swakActionGetNickName();
			var exists1 = swakDoesCharPrefContain(username, SMACK_USERNAMEHL1);
			if (exists1 == true) {
				var mi = document.getElementById('swaksmack-action-hl1');
				mi.setAttribute('label','Remove from Highlight List 1');
			}
			else {
				var mi = document.getElementById('swaksmack-action-hl1');
				mi.setAttribute('label','Add to Highlight List 1');
			}
			
			var exists2 = swakDoesCharPrefContain(username, SMACK_USERNAMEHL2);
			if (exists2 == true) {
				var mi = document.getElementById('swaksmack-action-hl2');
				mi.setAttribute('label','Remove from Highlight List 2');
			}
			else {
				var mi = document.getElementById('swaksmack-action-hl2');
				mi.setAttribute('label','Add to Highlight List 2');
			}
			
			var exists3 = swakDoesCharPrefContain(username, SMACK_USERNAMEHL3);
			if (exists3 == true) {
				var mi = document.getElementById('swaksmack-action-hl3');
				mi.setAttribute('label','Remove from Highlight List 3');
			}
			else {
				var mi = document.getElementById('swaksmack-action-hl3');
				mi.setAttribute('label','Add to Highlight List 3');
			}
			
			var fup = document.getElementById('swaksmack-action-find');
			var selectedName = null;
			try {
				if (gContextMenu && gContextMenu.searchSelected) 
					selectedName = gContextMenu.searchSelected();
				else
					selectedName = getBrowserSelection();
			}
			catch (x) {selectedName = null;}
			
			
			if (username == null) {
				fup.setAttribute('label','Find User\'s Posts');
			}
			else {
				var str = 'Find ';
				if (selectedName != null && selectedName != '') {
					str+=selectedName + '\'s Posts'
				}
				else {
					str+=username + '\'s Posts'
				}
				fup.setAttribute('label',str);
			}
			

		}
		
		function swakActionHighlight1() {
			var username = swakActionGetNickName();
			var exists = swakDoesCharPrefContain(username, SMACK_USERNAMEHL1);
			if (exists == false) {
				swakActionAddHighlightedUser(username,SMACK_USERNAMEHL1);
			}
			else {
				swakRemoveWordFromCharPref(username,SMACK_USERNAMEHL1);
				clearHighlightArrays();
			}
		}
		
	  function swakActionHighlight2() {
	  	var username = swakActionGetNickName();
			var exists = swakDoesCharPrefContain(username, SMACK_USERNAMEHL2);
			if (exists == false) {
				swakActionAddHighlightedUser(username,SMACK_USERNAMEHL2);
			}
			else {
				swakRemoveWordFromCharPref(username,SMACK_USERNAMEHL2);
				clearHighlightArrays();
			}
	  	
		}	
		
		function swakActionHighlight3() {
	  	var username = swakActionGetNickName();
			var exists = swakDoesCharPrefContain(username, SMACK_USERNAMEHL3);
			if (exists == false) {
				swakActionAddHighlightedUser(username,SMACK_USERNAMEHL3);
			}
			else {
				swakRemoveWordFromCharPref(username,SMACK_USERNAMEHL3);
				clearHighlightArrays();
			}
						
		}
		
		function swakActionFindUsersPosts() {
			var selectedName = null;
			try {
				if (gContextMenu && gContextMenu.searchSelected) 
					selectedName = gContextMenu.searchSelected();
				else
					selectedName = getBrowserSelection();
			}
			catch (x) {selectedName = null;}
			if (selectedName == null || selectedName == '') {
				selectedName = swakActionGetNickName();
			}
			if (selectedName == null || selectedName == '') return;
			findUsername(selectedName);
			//now clear any selected name/word
			try {
				swaksmack.postPopupNode.focus();
				swakClearCurrentSelection();
			}
			catch(x){}
		}
		
		function swakActionGetNickName() {
			try {
				var ctx = swaksmack.postPopupNode;
				var ci = getCommentInfo(ctx);
				var chatNick = getElementsByClassName('chatNick',ci);
				var username = chatNick[0].textContent;
				return username;
			}
			catch (x) {}
			return null;
		}
		
		function swakActionAddHighlightedUser(username, hlpref) {
			var result = swakAppendWordToCharPref(username,hlpref);
			if (result) {
				clearHighlightArrays();
				highlightExistingComments(swaksmack.SmackShopDoc);
			}					
		}		
		
		function swakActionPhotoAlbum() {
			var ctx = swaksmack.postPopupNode;
			var ci = getCommentInfo(ctx);
			var chatNick = getElementsByClassName('chatNick',ci);
			var ref = chatNick[0].getAttribute('href');
			var paurl = 'http://www.jellyfish.com' + ref + '/photoAlbum';
			Swak_openUrl(paurl,true);
		}
		
		function swakActionShoppingBuddies() {
			var ctx = swaksmack.postPopupNode;
			var ci = getCommentInfo(ctx);
			var chatNick = getElementsByClassName('chatNick',ci);
			var ref = chatNick[0].getAttribute('href');
			var paurl = 'http://www.jellyfish.com' + ref + '/shoppingBuddies';
			Swak_openUrl(paurl,true);
		}	

		function swakActionShoppingList() {
			var ctx = swaksmack.postPopupNode;
			var ci = getCommentInfo(ctx);
			var chatNick = getElementsByClassName('chatNick',ci);
			var ref = chatNick[0].getAttribute('href');
			var paurl = 'http://www.jellyfish.com' + ref + '/lists';
			Swak_openUrl(paurl,true);
		}																		

		function setChatSpeed() {
			try {
				var speed = SS_getPreference(SMACK_CHATSPEED);
				swaksmack.SS_JF.setChatSpeed(speed);
			}
			catch (Exception) {}
		}

		function updatePMLR() {
			var pmAlert = swaksmack.SmackShopDoc.getElementById('alertEnvelope');
			var contextAlert = content.document.getElementById('alertEnvelope');
			if ((pmAlert != null && pmAlert.className == 'new') || (contextAlert != null && contextAlert.className == 'new')) {
				swaksmack.SS_SBM.flashPMButton(-1);
			///	swaksmack.SS_SBM.setPMStatusOn();
			}
			else if ((pmAlert != null && pmAlert.className == 'noNew') || (contextAlert != null && contextAlert.className == 'noNew')) {
				swaksmack.SS_SBM.setPMStatusOff();
			}
			
			var chatAlert= swaksmack.SmackShopDoc.getElementById('alertChat');
			contextAlert = content.document.getElementById('alertChat');
			if ((chatAlert != null && chatAlert.className == 'new') || (contextAlert != null && contextAlert.className == 'new')) {
				swaksmack.SS_SBM.setLRStatusOn();
			}
			else if ((chatAlert != null && chatAlert.className == 'noNew') || (contextAlert != null && contextAlert.className == 'noNew')) {
				swaksmack.SS_SBM.setLRStatusOff();
			}
		}
		
		
		function onPMUpdate(prevPM, pmValue, prevChat, chatValue) {
			//alert(pmValue+ ' onPMUpdate ' + chatValue);
			//if there is change, update the main smack page and any current page indicator
			if (pmValue != prevPM) {
				var pmAlert = swaksmack.SmackShopDoc.getElementById('alertEnvelope');
				var contextAlert = content.document.getElementById('alertEnvelope');
				if (pmValue == true) {
					pmAlert.className = '';
					if (contextAlert != null && contextAlert != 'undefined') contextAlert.className = '';
					swaksmack.SS_SBM.flashPMButton(-1);
				///	swaksmack.SS_SBM.setPMStatusOn();
				}
				else {
					pmAlert.className = 'noNew';
					if (contextAlert != null && contextAlert != 'undefined') contextAlert.className = 'noNew';
					swaksmack.SS_SBM.setPMStatusOff();
				}
			}
			if (chatValue != prevChat) {
				var chatAlert= swaksmack.SmackShopDoc.getElementById('alertChat');
				contextAlert = content.document.getElementById('alertChat');
				if (chatValue == true) {
					chatAlert.className = '';
					if (contextAlert != null && contextAlert != 'undefined') contextAlert.className = '';
					swaksmack.SS_SBM.setLRStatusOn();
				}
				else {
					chatAlert.className = 'noNew';
					if (contextAlert != null && contextAlert != 'undefined') contextAlert.className = 'noNew';
					swaksmack.SS_SBM.setLRStatusOff();
				}
			}
		}



		//guru guess calc
		function launchCalcWindow() {
			//swaksmack.alertManager.swakAlert(SMACK_ALERT_CUSTOM, true, 5000, true);
			if (SS_GGCalcWindow == null || SS_GGCalcWindow.closed == true) {
	
				SS_GGCalcWindow=window.open('chrome://swaksmack/content/ggcalc.xul','SwakSmack Guru Calculator','height=400,width=500');
	
			}
			else {
				//we close and then create a new window because some of the elements
				//the popup depends on are replaced whem the liveconatinerobject has
				//its innherhtml updated
				SS_GGCalcWindow.close();
	
				SS_GGCalcWindow=window.open('chrome://swaksmack/content/ggcalc.xul','SwakSmack Guru Calculator','height=400,width=500');
	
	
			}
	
	
			//create popup object--revisit
			if ( SS_ggcalc == null) {
				SS_ggcalc = new GGCalc();
			}
			SS_ggcalc.popup=SS_GGCalcWindow;
		}
	
		function SS_onOptionsUpdate() {
			clearHighlightArrays();
		}

		var swakalerts = {
			outwitAlertAck: false,
			outwitVoteAck: false,
			smakpotAlertAck: false,
			guruguessAlertAck: false
		}

		var swaksmack = {
			jfdoc:null,
			SS_SBM:null,
			SS_JF:null,
			SmackShopDoc:null,
			LivingRoomDoc:null,
			alertManager:null,
			audioManager:null,
			smackchatIdArray:null,
			smackLRIdArray:null,
			smackShopContentWindow:null,
			smackCommentsHidden: false,
			lrCommentsHidden: false,
			ignoreListCurrent: false,
			lastPMCheckTime: null,
			PMChecker: null,
			coinsWonDuringShow: 0,
			coinsWonOnLastItem: 0,
			coinsWonDuringSession: 0,
			productListenerAdded: false,
			postPopupNode: null,
			actionPopup: null,
			setdoc: function(d) {
				swaksmack.jfdoc = d;
			},
			onLoad: function() {
				getBrowser();
				// initialization code
				this.initialized = true;
				this.strings = document.getElementById("swaksmack-strings");
				document.getElementById("contentAreaContextMenu")
				.addEventListener("popupshowing", function(e) { this.showContextMenu(e); }, false);
				//add onload listener for web pages
				var appcontent = document.getElementById("appcontent");   // browser
				if(appcontent) {
					appcontent.addEventListener("load", this.onPageLoad, true);
					appcontent.addEventListener("load", this.showContextMenu, true);
					//test
					appcontent.addEventListener("unload", this.onPageUnload, true);
				}

				SwakPrefWatcher.init();


			},
			onPageLoad: function(aEvent) {
				var doc = aEvent.originalTarget; // doc is document that triggered "onload" event
				// do something with the loaded page.
				// doc.location is a Location object (see below for a link).
				// You can use it to make your code executed on certain pages only.


				if (checkHost(doc) == true) {
					//alert('onpageload');
					//create a UID for this session
					//swaksmack.swakdate = new Date();
					//SS_UID = swaksmack.swakdate.getTime();

					if (swaksmack.SS_JF == null) {
						swaksmack.SS_JF = new JellyFish();
					}

					swaksmack.smackLRIdArray = new Array();

					var shoppingArea = false;
					shoppingArea = isSmackShopArea(doc);
					//alert('JF smack aread found ' + shoppingArea);
					//store doc ref for smack shopping document
					if (shoppingArea == true) {
						//alert('smack area found');
						swaksmack.SmackShopDoc = doc;
						SS_window = window;
						swaksmack.smackShopContentWindow = gBrowser.contentWindow;
						//alert(gBrowser.contentWindow + ', gBrowser.contentWindow, swaksmack.smackShopContentWindow ' + swaksmack.smackShopContentWindow);
						swaksmack.smackchatIdArray = new Array();
						registerSmackChatListeners(swaksmack.SmackShopDoc);
						updateDisplayHighlightedUI(swaksmack.SmackShopDoc);
						updateChatThemeCSS(swaksmack.SmackShopDoc);
						addPlayPause(swaksmack.SmackShopDoc);
					}

					//enable for offline guruguess test
					if (false) {
						//temp for gg calc test
						swaksmack.SmackShopDoc = doc;
						registerSmackChatListeners(swaksmack.SmackShopDoc);
					}

					//check to see if in the private message area


					if (isPMArea(doc) == true) {
						executePMLink(SMACK_PMDIV, doc);
						return;
					}
					else if (isLRArea(doc) == true) {
						swaksmack.LivingRoomDoc = doc;
						registerLivingRoomChatListeners(swaksmack.LivingRoomDoc);
						updateDisplayHighlightedUI(swaksmack.LivingRoomDoc);
					}
					//	alert('onpageload');
					commentSpellCheck(doc);
					chatLinkColor(doc);

					clearHighlightArrays();



					//register listener on the chat post for tinyurl
					registerChatPostListener(doc);
					//SS_AM = new SSAlertManager();
					if (swaksmack.alertManager == null)
					swaksmack.alertManager = new SSAlertManager();
					if (swaksmack.audioManager == null)
					swaksmack.audioManager = new AudioManager();

					swaksmack.SS_SBM.setKWStatusConnected();
					if (shoppingArea == true) {
						swaksmack.SS_SBM.monitorState(SS_getPreference(SMACK_SBSALEINTERVAL));
					}
					else {
						//alert('not shopping area');
					}

					// SS_SBM.hideStatusBar(true);

					if (SS_getPreference(SMACK_CHECKPMCHAT) == true) {
						if (swaksmack.PMChecker != null) {
							swaksmack.PMChecker.stopCheck();
						}
						swaksmack.PMChecker = new JellyFishPMChecker();
						swaksmack.PMChecker.setInterval(SS_getPreference(SMACK_CHECKPMINTERVAL));
						swaksmack.PMChecker.checkPM();
					}

					//menu stuff

					var menu = document.getElementById("contentAreaContextMenu");
					//alert(menu);
					menu.addEventListener("popupshowing", swakContextShowing, false);
					swakContextVisibilityOn();

					//http://developer.mozilla.org/en/docs/Code_snippets:Tabbed_browser#Closing_a_tab
					var container = gBrowser.tabContainer;
					container.addEventListener("TabClose", swaksmack.tabRemoved, false);
					container.addEventListener("TabSelect", swaksmack.tabSelected, false);
					//container.addEventListener("TabClose", function(e) { alert('af tab removed'); }, false);

					if (SS_getPreference(SMACK_ENHANCEHIDEAVATARS)) {
						hideAllAvatarImages();
					}


					swaksmack.setdoc(doc);
					swaksmack.actionPopup = document.getElementById('swaksmackActions');
					
					//late init stuff
					if (swaksmack.smackShopContentWindow == null || swaksmack.SmackShopDoc == null) {
						if (isSmackShopArea(doc) == true) {
							//alert('late initialization of smackShopContentWindow');
							swaksmack.smackShopContentWindow = gBrowser.contentWindow;
							swaksmack.SmackShopDoc = doc;
						}
					}

				}
			},
			onPageUnload: function(aEvent) {
				try {
					var doc = aEvent.originalTarget;
					//var doc = aEvent.target;
					var	host = doc.location.host;
					if (swaksmack.smackShopContentWindow == gBrowser.contentWindow) {
						//var doc = aEvent.originalTarget;
						if (checkHost(doc) == true && isSmackShopArea(doc)) {
							swaksmack.updateConnectedStatus(aEvent);
							swaksmack.SS_SBM.stopMonitorState();
						}
						updateDisplayHighlightedUI(swaksmack.SmackShopDoc);
						swaksmack.dispose();
					}
				}
				catch(x){}


			},
			showContextMenu: function(event) {
				// show or hide the menuitem based on what the context menu is on
				// see http://kb.mozillazine.org/Adding_items_to_menus
				//document.getElementById("context-jellyfish").hidden = gContextMenu.onImage;  //org
				//document.getElementById("context-swacksmack").hidden = !checkHost();
			},
			onMenuItemCommand: function(e) {

				//no longer needed for chat/url processing --remove menu item???
				//execute(SMACK_OUTWITCHATDIV);
				//externalLinks();


			},
			tabRemoved: function(event) {
				try {
					var browser = event.target.linkedBrowser;
					//alert('jf tab removed ' + event.originalTarget);
					var doc = content.document;
					if (swaksmack.smackShopContentWindow == browser.contentWindow) {
						//alert('browser.contentWindow is ss contwindow');
						if (checkHost(doc) == true && isSmackShopArea(doc)) {
							//67 swaksmack.updateConnectedStatus(event);
							//67 swaksmack.SS_SBM.stopMonitorState();
						}
						swaksmack.updateConnectedStatus(event);
						swaksmack.SS_SBM.stopMonitorState();
						updateDisplayHighlightedUI(swaksmack.SmackShopDoc);
						swaksmack.dispose();
					}
				}
				catch(x){}


			},
			dispose: function() {
				if (swaksmack.PMChecker != null) {
					swaksmack.PMChecker.stopCheck();
					swaksmack.PMChecker = null;
				}
				swaksmack.smackShopContentWindow = null;
				//alert('dispose --swaksmack.smackShopContentWindow reference set to null');
				swaksmack.smackCommentsHidden = false;
				swaksmack.smackchatIdArray = [];
				JF_ignoreUserlistRegExp = null;
				JF_ignoreWordlistRegExp = null;
				JF_ignoreAttendancelistRegExp = null;
				JF_keywordlistRegExp = null;
				JF_usernamelistRegExp = null;
				JF_usernameArray = [];
				JF_keywordArray = [];
			},
			tabSelected: function(event) {
				try {

					updateDisplayHighlightedUI(content.document);
					//alert('tabselected updated display UI');
				}
				catch (x){}
			},
			updateConnectedStatus: function(event) {
				//alert(' swak updateConnectedStatus ');
				if (swaksmack.SS_SBM == null)
				swaksmack.SS_SBM = new StatusBarManager();
				swaksmack.SS_SBM.setKWStatusDisabled();
				swaksmack.SS_SBM.setSaleStatusDisconnected();


			},
			getUserGuess: function() {
				if (swaksmack.SmackShopDoc == null) return null;
				//alert('ss testdoc' + swaksmack.testdoc);
				return  swaksmack.SmackShopDoc.getElementsByName('user_guess');
			}

		};

			var SwakPrefWatcher = {
				prefs: null,
				hlUpdated: false,
				themeUpdated: false,
				init: function() {
					this.prefs = Components.classes["@mozilla.org/preferences-service;1"]
					.getService(Components.interfaces.nsIPrefService)
					.getBranch("extensions.swaksmack.");
					this.prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
					this.prefs.addObserver("", this, false);
					this.initStatusBar();
					this.initAudio();
					this.initAlerts();


				},
				initStatusBar: function() {
					if (swaksmack.SS_SBM == null) {
						//SS_SBM = new StatusBarManager();
						swaksmack.SS_SBM = new StatusBarManager();
						var sb1 = document.getElementById('swak-sb-kw-status');
						swaksmack.SS_SBM.setKWStatusBarPanel(sb1);

						var sbpm = document.getElementById('swak-sb-pm-status');
						swaksmack.SS_SBM.setPMStatusBarPanel(sbpm);

						var sblr = document.getElementById('swak-sb-lr-status');
						swaksmack.SS_SBM.setLRStatusBarPanel(sblr);

						var sbsale = document.getElementById('swak-sb-sale-status');

						swaksmack.SS_SBM.setSaleStatusBarPanel(sbsale);
					}
					var hid = this.prefs.getBoolPref("appearance.displaystatusbarpm_boolpref1");
					swaksmack.SS_SBM.hidePM(!hid);

					hid = this.prefs.getBoolPref("appearance.displaystatusbarlr_boolpref1");
					swaksmack.SS_SBM.hideLR(!hid);

					hid = this.prefs.getBoolPref("appearance.displaystatusbarkw_boolpref1");
					swaksmack.SS_SBM.hideKW(!hid);

					hid = this.prefs.getBoolPref("appearance.displaystatusbarsale_boolpref1");
					swaksmack.SS_SBM.hideSale(!hid)
				},
				initAudio: function() {
					var audio = document.getElementById('ss-sb-pu-audio');
					var enabled = this.prefs.getBoolPref("audio.global_enable_boolpref");
					audio.setAttribute('checked',enabled);

				},
				initAlerts: function() {
					var alerts = document.getElementById('ss-sb-pu-alerts');
					var enabled = this.prefs.getBoolPref("alerts.global_enable_boolpref");
					alerts.setAttribute('checked',enabled);

				},
				shutdown: function() {
					this.prefs.removeObserver("", this);
				},
				onUpdate: function() {
					//alert('prefs updated');
					if (this.themeUpdated == true) {
						updateChatThemeCSS(swaksmack.SmackShopDoc);
					}
					if (this.hlUpdated == true) {
						clearHighlightArrays();
						highlightExistingComments(swaksmack.SmackShopDoc);
					}
					this.hlUpdated = false;
					this.themeUpdated = false;
				},
				observe: function(subject, topic, data) {
					if (topic != "nsPref:changed") {
						return;
					}

					switch(data) {
						case "appearance.displaystatusbarpm_boolpref1":
							if (swaksmack.SS_SBM == null) return;
							var hid = this.prefs.getBoolPref("appearance.displaystatusbarpm_boolpref1");
							swaksmack.SS_SBM.hidePM(!hid);
							break;
						case "appearance.displaystatusbarlr_boolpref1":
							if (swaksmack.SS_SBM == null) return;
							var hid = this.prefs.getBoolPref("appearance.displaystatusbarlr_boolpref1");
							swaksmack.SS_SBM.hideLR(!hid);
							break;
						case "appearance.displaystatusbarkw_boolpref1":
							if (swaksmack.SS_SBM == null) return;
							var hid = this.prefs.getBoolPref("appearance.displaystatusbarkw_boolpref1");
							swaksmack.SS_SBM.hideKW(!hid);
							break;
						case "appearance.displaystatusbarsale_boolpref1":
							if (swaksmack.SS_SBM == null) return;
							var hid = this.prefs.getBoolPref("appearance.displaystatusbarsale_boolpref1");
							swaksmack.SS_SBM.hideSale(!hid);
							break;
						case "audio.global_enable_boolpref":
							var enabled = this.prefs.getBoolPref("audio.global_enable_boolpref");
							var audio = document.getElementById('ss-sb-pu-audio');
							audio.setAttribute('checked',enabled);
							break;
						case "alerts.global_enable_boolpref":
							var enabled = this.prefs.getBoolPref("alerts.global_enable_boolpref");
							var alerts = document.getElementById('ss-sb-pu-alerts');
							alerts.setAttribute('checked',enabled);
							break;
						case "hl.usernamehl1_stringpref":
						case "hl.usernamehl2_stringpref":
						case "hl.usernamehl3_stringpref":
							this.hlUpdated = true;
							//clearHighlightArrays();
							//highlightExistingComments(swaksmack.SmackShopDoc);
							break;
						case "hl.keywordshl1_stringpref":
						case "hl.keywordshl2_stringpref":
						case "hl.keywordshl3_stringpref":
						case "hl.ignorecasehl_boolpref1":
						case "hl.chatwildcard1_boolpref1":
						case "hl.chatwildcard2_boolpref1":
						case "hl.chatwildcard3_boolpref1":
						case "hl.dynamicusername_stringpref":
						case "hl.dynamickeyword_stringpref":
						case "hl.chatinfohl1_boolpref1":
						case "hl.chatinfohl2_boolpref1":
						case "hl.chatinfohl3_boolpref1":
						case "hl.enablehl1_boolpref1":
						case "hl.enablehl2_boolpref1":
						case "hl.enablehl3_boolpref1":
							this.hlUpdated = true;
							break;
						case "ignore.ignorelist1_stringpref":
						case "ignore.ignorelist2_stringpref":
						case "ignore.ignorelistattend1_stringpref":
							swaksmack.ignoreListCurrent = true;
							JF_ignoreUserlistRegExp = null;
							JF_ignoreWordlistRegExp = null;
							JF_ignoreAttendancelistRegExp = null;
							break;
						case "theme.enabletheme_boolpref1":
						case "theme.textcolor1_stringpref":
						case "theme.bkcolor1_stringpref":	
						case "theme.chatActions_stringpref":
							this.themeUpdated = true;
							//updateChatThemeCSS(swaksmack.SmackShopDoc);
							break;
						case "options.updated_boolpref":
							var updateComplete = this.prefs.getBoolPref("options.updated_boolpref");
							if (updateComplete == true) {
								this.onUpdate();
							}
							this.hlUpdated = false;
							this.themeUpdated = false;
							break;	
					}
				}

			}
			window.addEventListener("load", function(e) { swaksmack.onLoad(e); }, false);

